Linux: Difference between revisions

From 太極
Jump to navigation Jump to search
 
Line 1: Line 1:
== Handy Linux tips ==
= man =
* [https://www.howtogeek.com/663440/how-to-use-linuxs-man-command-hidden-secrets-and-basics/ How to Use Linux’s man Command: Hidden Secrets and Basics]
* [https://www.maketecheasier.com/read-linux-man-page/ How to Easily Read a Linux Man Page]
** Underlined or Italicized Text: It means you need to replace it with an appropriate argument.
** Ellipses: It means that argument or expression is repeatable.


=== Beautiful desktop ===
== Navigation ==
* http://lifehacker.com/the-aincrad-desktop-1732684767
[https://wiki.gentoo.org/wiki/Man_page/Navigate Gentoo] and [https://fossbytes.com/linux-lexicon-man-pages-navigation/ fossbytes]
* http://lifehacker.com/the-distant-pyramid-desktop-1654404411
 
* http://lifehacker.com/the-flat-n-fuzzy-desktop-1693121677
* Enter – Move down one line
* http://lifehacker.com/the-midsummer-nights-desktop-1704207155
* Space – Move down one page
* g – Move to the top of the page
* G – Move to the bottom of the page
* q – Quit
 
== Search within a man page ==
Use / and type your search pattern.
 
Use 'n' for forward search and 'N' for reverse search.
 
The matched line will be moved to the top of the screen.
 
By default, the search is case insensitive or we can use '''man -i COMMAND'''.
 
Regular expression is supported. For example to find all of the long arguments with: /(--)[a-Z]


=== Virtual consoles ===
== Colored man pages ==
Linux allows ''virtual consoles'' (aka ''virtual terminals'') to be opened while an ''X Window System'' is executing.
<span style="color: red">This is a cool tip!</span>


Use Ctrl+Alt+F1 to open a virtual console-- there are six virtual text-based consoles (F1 to F6). Use Ctrl+Alt+F7 to return to the X Window System.
By default, the man program normally uses a terminal '''pager''' program such as '''less''' to format its output.


=== How much resource is used by a process ===
[https://www.tecmint.com/view-colored-man-pages-in-linux/ Add the following to "~/.bashrc" file]. For example, '''LESS_TERMCAP_mb''' customizes the appearance of blink text in the '''less''' pager (or '''man''' command) and '''LESS_TERMCAP_us''' customizes the appearance of underlined text in the '''less''' pager.
Find the process ID first by ps -ef | grep APPLICATIONAME. Then
<pre>
<pre>
ps -p <pid> -o %cpu,%mem,cmd
# Customize less colors
</pre>
export LESS_TERMCAP_mb=$'\e[1;32m' # Blinking text: bold green
For example,
export LESS_TERMCAP_md=$'\e[1;34m' # Bold text: bold blue
<pre>
export LESS_TERMCAP_me=$'\e[0m'    # End mode
$ ps -ef | grep akregator
export LESS_TERMCAP_so=$'\e[01;47;34m'  # Standout: bold white on blue
brb      15013  1942 1 10:41 ?        00:00:05 akregator --icon akregator -caption Akregator
export LESS_TERMCAP_se=$'\e[0m'    # End standout mode
brb      15186 24045 0 10:50 pts/11  00:00:00 grep --color=auto akregator
export LESS_TERMCAP_us=$'\e[1;4;31m' # Underlined text: bold underlined red
$ ps -p 15013 -o %cpu,%mem,cmd
export LESS_TERMCAP_ue=$'\e[0m'    # End underline
%CPU %MEM CMD
1.0 0.8 akregator --icon akregator -caption Akregator
</pre>
</pre>


=== Query whether the OS is 64-bit or 32-bit ===
(New way, The '''most''' Pager) [https://www.cyberciti.biz/faq/unix-linux-color-man-pages-configuration/ How To Display Color Man Pages in Linux and Unix] or [https://www.howtogeek.com/683134/how-to-display-man-pages-in-color-on-linux/ How to Display man Pages in Color on Linux].
<pre>
SYSTEM_ARCH=getconf LONG_BIT
echo $SYSTEM_ARCH
</pre>


=== Switch user in command line ===
== Navigate to another man page within a man page ==
use <pre>su newusername</pre> to switch to another user.
See [https://stackoverflow.com/a/38604548 here].


=== Directory permission / attribute ===
When inside the man page, press ! followed by a valid shell command.
See http://unix.stackexchange.com/questions/21251/how-do-directory-permissions-in-linux-work


When applying permissions to directories on Linux, the permission bits have different meanings than on regular files.
For example : !man cat


* The write bit allows the affected user to create, rename, or delete files within the directory, and modify the directory's attributes
== View a specific "Section" ==
* The read bit allows the affected user to list the files within the directory
* [https://unix.stackexchange.com/a/3587 What do the numbers in a man page mean?]
* '''The execute bit allows the affected user to enter the directory, and access files and directories inside'''
* [https://superuser.com/questions/357048/how-do-you-switch-between-linux-manual-pages How do you switch between Linux manual pages?]


When we create a new directory, the attribute is 775. Some pre-created directories (Desktop, Documents, Music, Pictures, Public) have an attribute 755.  
{{Pre}}
$ whatis printf
printf (1)          - format and print data
printf (3)          - formatted output conversion
Printf (3o)         - Formatted output functions.
$ man 3 printf
</pre>


=== Find binary file location ===
== Read man pages in vi without using temporary files ==
* '''which''' - Display the full path of shell commands. See examples from [http://www.cyberciti.biz/faq/unix-linux-which-command-examples-syntax-to-locate-programs/ cyberciti.biz].
[https://stackoverflow.com/a/16740302 What is a way to read man pages in vim without using temporary files]
<pre>
{{Pre}}
$ which ls
man find | vi -
/bin/ls
</pre>
* '''whereis''' - locate the binary, source, and manual page files for a command. See examples from [http://www.cyberciti.biz/faq/unix-linux-whereis-command-examples-to-locate-binary/ cyberciti.biz]
<pre>
$ whereis ls
ls: /bin/ls /usr/share/man/man1p/ls.1p.gz /usr/share/man/man1/ls.1.gz
</pre>
* '''type -a'''
<pre>
$ type -a ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
</pre>
</pre>


Use '''locate''' command mindfully. It is used to find the location of files and directories. Note that locate does not search the files on disk rather it searches for file paths in a database.
== Search man page referenced by ==
For example, the following command will search .png files over the system (not only the personal directory).
'''man -f KEYWORD'''
<pre>
locate "*.png"
</pre>


=== IP address fundamental ===
This command is equivalent to '''whatis -r KEYWORD'''
http://www.howtogeek.com/133943/geek-school-learning-windows-7-ip-addressing-fundamentals/


=== Change to root shell ===
== Search from all man pages ==
The following command will switch to an environment similar to what the user would expect had the user logged in directly.
'''man -k KEYWORD''' will give you a list of all man pages which relate to 'KEYWORD'.
<syntaxhighlight lang='bash'>
sudo su -
</syntaxhighlight>
This can be useful when running 'su' or 'su -' failed because of authentication failure.
 
See also
* [https://wiki.archlinux.org/index.php/su wiki.archlinux.org].
* Difference of 'su', 'sudo -s' and 'sudo -i' from [http://askubuntu.com/questions/70534/difference-between-su-sudo-s-sudo-i askubuntu.com].


For sudo to work, my account ('debian' in this case) has to be included in the config file '''/etc/sudoers'''.
== TLDR pages/cheat sheet: alternative to Man ==
<pre>
<ul>
debian  ALL=NOPASSWD: ALL
<li>https://tldr.sh/ </li>
<li>[https://fossbytes.com/tldr-pages-linux-man-pages-alternative/ TLDR pages: Simplified Alternative To Linux Man Pages]. Be sure to install the latest versions of [[Node.js|nodejs and npm]]. Tested on Ubuntu 16.04, 20.04. Example:
{{Pre}}
$ npm install -g tldr
$ tldr tar
</pre>
</pre>
When sudo is invoked, it asks for the password of the user who started it.
</li>
<li>[https://ostechnix.com/display-linux-commands-cheatsheets-with-tealdeer-tool/ Display Linux Commands Cheatsheets With Tealdeer In Terminal]
A full list of commands is on [https://tldr.sh/assets/tldr-book.pdf TLDR Pages]. </li>
</ul>


==== Switch to another user and run a command using su -c ====
== Cheat.sh (better than TLDR) ==
* http://unix.stackexchange.com/questions/156343/pass-arguments-to-a-command-run-by-another-user
[https://www.linuxuprising.com/2019/07/cheatsh-shows-cheat-sheets-on-command.html?m=1 Cheat.sh Shows Cheat Sheets On The Command Line Or In Your Code Editor]. There are different ways to use it. One way does not require to install anything as long as we have the '''curl''' command.
* http://unix.stackexchange.com/questions/87860/how-does-this-su-c-command-seem-to-pass-two-commands-instead-of-one
{{Pre}}
curl cheat.sh/tar


Example:
curl cht.sh/python/random+list # Python programming language cheat sheet for random list
<syntaxhighlight lang='bash'>
</pre>
sudo su - -c "R -q -e \"install.packages('mypackage', repos='http://cran.rstudio.com/')\""
My test shows cheat.sh can find more commands and it gives colored output.


man su
= Some books =
</syntaxhighlight>
* UNIX in a nutshell
* sed & awk
* lex & yacc
* bash
* [http://proxy.montgomerylibrary.org:2051/book/programming/linux/9781491927557 Linux Pocket Guide]
* bash cookbook: pdf is online
* Classic Shell Scripting
* GNU EMACS
* Learning the vi and Vim editors 7th
* UNIX POWER TOOLS
* [http://proxy.montgomerylibrary.org:2051/book/operating-systems-and-server-administration/bash/9781491941584 Bash Pocket Reference]
* System Administration 3rd
* TCP/IP 3rd: pdf is online
* DNS and BIND 5th
* Network Troubleshooting Tools
* [https://itsfoss.com/learn-linux-for-free/ 25 Free Books To Learn Linux For Free]
* [https://opensource.com/article/18/5/list-books-Linux-open-source 17 books for Linux and open source fans]


=== Bash shell programming ===
= Beautiful desktop =
http://bash.cyberciti.biz/guide/Main_Page
* http://lifehacker.com/the-aincrad-desktop-1732684767
 
* http://lifehacker.com/the-distant-pyramid-desktop-1654404411
=== Redirect standard error ===
* http://lifehacker.com/the-flat-n-fuzzy-desktop-1693121677
http://bash.cyberciti.biz/guide/Standard_error. Use '''2>''' operator.
* http://lifehacker.com/the-midsummer-nights-desktop-1704207155
<pre>
command 2> errors.txt
</pre>


=== ls | more without lose color ===
== .desktop file ==
<pre>
This is not related to ''beautiful desktop''. It is used to launch applications in Linux. Without the .desktop file, your application won’t show up in the Applications menu and you can’t launch it with third-party launchers such as Synapse and [https://www.maketecheasier.com/albert-launcher-linux/ Albert Launcher].
ls --color | more
</pre>
Most likely your ls is aliased to ls --color=auto. If you do ls --color (which is morally equivalent to ls --color=always), that will force it to turn on colors.


=== ls output with color background ===
* https://wiki.archlinux.org/index.php/Desktop_entries
[http://unix.stackexchange.com/questions/94498/what-causes-this-green-background-in-ls-output stackexchange] or [http://askubuntu.com/questions/17299/what-do-the-different-colors-mean-in-the-terminal askubuntu].
* https://www.maketecheasier.com/create-desktop-file-linux/


In my case, after I apply '''chmod 755 -R XXXX''', the weird green background color goes away.
The .desktop files are commonly saved in
* ~/local/share/applications
* /usr/share/applications


=== colordiff-color in terminal diff ===
== List of installed desktop environment ==
PS. For a GUI version of diff, [http://meldmerge.org/ Meld] works fine.
Need to install first. apt-get install colordiff. http://www.cyberciti.biz/programming/color-terminal-highlighter-for-diff-files/
<pre>
<pre>
sudo apt-get install colordiff
ls -l /usr/share/xsessions/
diff -y file1 file2 | colordiff
# Ignore same rows (two ways):
# diff -C0 file1 file2 | colordiff
# diff -U0 file1 file2 | colordiff
</pre>
</pre>
where -y option means to show the output in two columns.


[[File:Colordiff.png|150px]]
== Themes ==
[https://www.maketecheasier.com/best-linux-dark-themes/ 5 of the Best Linux Dark Themes that Are Easy on the Eyes]
 
= Virtual consoles/virtual terminals =
Linux allows ''virtual consoles'' (aka ''virtual terminals'') to be opened while an ''X Window System'' is executing.
 
Use '''Ctrl + Alt + FX''' to open a virtual console-- there are six virtual text-based consoles (F1 to F6). Use '''Alt + F7''' (or possibly other keybinds) to return to the X Window System.


Interpretation of the '''diff''' output:
[https://opensource.com/article/16/11/managing-devices-linux Managing devices in Linux] -> Fun with device files.


The first line of the '''diff''' output will contain:
== Change/increase console fonts ==
* line numbers corresponding to the first file,
* https://www.linux.com/learn/intro-to-linux/2018/1/how-change-your-linux-console-fonts
* a letter ('''a''' for add, '''c''' for change, or '''d''' for delete), and
* https://youtu.be/LOg4xfDQafc
* line numbers corresponding to the second file.


In our output above, '''2,4c2,4''' means: "Lines 2 through 4 in the first file need to be changed in order to match lines 2 through 4 in the second file." It then tells us what those lines are in each file:
= Desktops/Workspaces =
'''Ctrl + Alt + ->''' or '''Ctrl + Alt + <-''' to switch workspaces.


* Lines preceded by a < are lines from the first file;
'''Ctrl + Alt + down''' can list the open applications on the current workspace.
* lines preceded by > are lines from the second file.
 
* The three dashes ("---") merely separate the lines of file 1 and file 2.
'''Ctrl + Alt + up''' can show all workspaces and the open applications. We can use mouse to move an app to any workspace.
<pre>
 
2,4c2,4
'''SuperKey + left''' tile a window to left. '''SuperKey + right''' tile a window to right.
< I need to run the laundry.
 
< I need to wash the dog.
[https://www.lifewire.com/complete-list-of-linux-mint-4064592 Complete List of Linux Mint 18 Keyboard Shortcuts for Cinnamon] for more examples.
< I need to get the car detailed.
 
---
= Mouse =
> I need to do the laundry.
[https://www.linuxuprising.com/2019/11/how-to-bind-mouse-buttons-to-keyboard.html?m=1 How To Bind Mouse Buttons To Keyboard Keys Or Commands (Linux Using X11)]
> I need to wash the car.
> I need to get the dog detailed.
</pre>


=== Run diff with large files ===
= Virtual memory =
Meld freezes When I tested it with two large files (800k & 936k lines coming from human gtf files). Actually the whole linux system became unresponsive.


=== Count number of columns: awk ===
== vmstat ==
The following command shows the number of columns for the first few rows of a text file.
* [http://www.2daygeek.com/linux-vmstat-command-examples-tool-report-virtual-memory-statistics/ '''vmstat''' – A Standard Nifty Tool to Report Virtual Memory Statistics]
<syntaxhighlight lang="bash">
* [https://www.howtogeek.com/424334/how-to-use-the-vmstat-command-on-linux/ How to Use the vmstat Command on Linux]
head MYFILE | awk '{ print NF}'


head MYFILE | awk -F '\t'  '{ print NF}'
== hcache ==
</syntaxhighlight>
A tool fork from pcstat, with a feature that showing top X biggest cache files globally
* https://github.com/silenceshell/hcache
* http://www.datastart.cn/tech/2017/05/20/hcache.html


=== Count number of rows in a file: wc ===
= Memory: free command =
<syntaxhighlight lang="bash">
* [https://www.makeuseof.com/tag/manage-linux-ram/ Is Linux Eating Your RAM? How to Manage Your Memory]
wc -l MYFILE
* [https://www.howtogeek.com/456943/how-to-use-the-free-command-on-linux/ How to Use the free Command on Linux] (*detailed and comprehensive)
</syntaxhighlight>
* [https://www.howtogeek.com/659529/how-to-check-memory-usage-from-the-linux-terminal/ How to Check Memory Usage From the Linux Terminal]


The source code of wc (or any Linux command) can be found by using [http://ubuntuforums.org/showthread.php?t=241328 this method]
Three types of memory reported by the '''free''' command.
<syntaxhighlight lang="bash">
* Used: RAM that is currently in use by an application.
brb@brb-T3500:~/Downloads$ which wc
* Available: RAM that may be in use for disk caching but can be freed up for applications. [https://stackoverflow.com/a/41426746 What is 'available' vs 'free' memory in free command?]. '''Available = Estimation of how much memory is available for starting new applications, without swapping.'''
/usr/bin/wc
* Shared: Amount of memory used by the tmpfs file systems.
brb@brb-T3500:~/Downloads$ dpkg -S /usr/bin/wc
* Free: RAM that is not in use by an application or disk caching.
coreutils: /usr/bin/wc
* '''Total =  Used + Free + Buffers/Cache'''
brb@brb-T3500:~/Downloads$ sudo apt-get source coreutils
[sudo] password for brb:
Reading package lists... Done
Building dependency tree     
Reading state information... Done
Need to get 12.3 MB of source archives.
Get:1 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main coreutils 8.21-1ubuntu5.1 (dsc) [1,635 B]
Get:2 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main coreutils 8.21-1ubuntu5.1 (tar) [12.3 MB]
Get:3 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main coreutils 8.21-1ubuntu5.1 (diff) [31.6 kB]
Fetched 12.3 MB in 22s (559 kB/s)                                             
gpgv: Signature made Tue 13 Jan 2015 10:33:04 PM EST using RSA key ID 9D8D2E97
gpgv: Cannot check signature: public key not found
dpkg-source: warning: failed to verify signature on ./coreutils_8.21-1ubuntu5.1.dsc
dpkg-source: info: extracting coreutils in coreutils-8.21
dpkg-source: info: unpacking coreutils_8.21.orig.tar.gz
dpkg-source: info: applying coreutils_8.21-1ubuntu5.1.diff.gz
</syntaxhighlight>


As we can see from the ''coreutils-8.21/src'' directory, there are over 100 C programs including <cat.c>, <chmod.c>, <cp.c>, ...<wc.c>.
How to Clear RAM Memory Cache and Buffer
{{Pre}}
# To clear pagecache, enter the following command:
echo 1 > /proc/sys/vm/drop_caches


=== Print certain rows/lines of a text file ===
# To clear dentries and inodes, change the number to 2:
The following example will print out lines 10 to 60 of FILENAME.
echo 2 > /proc/sys/vm/drop_caches
<pre>
 
sed -n '10,60p' FILENAME
# To clear pagecache, dentries, and inodes all together, change the number to 3:
echo 3 > /proc/sys/vm/drop_caches
</pre>
</pre>
Or to print out line 60,
 
== How do I determine the number of RAM slots in use ==
<pre>
<pre>
sed -n '60p' FILENAME
sudo dmidecode -t memory
</pre>
</pre>
It seems this method is not as fast as I expected. For example, the '''tail''' command will immediately print out the result without waiting!
=== output colored console to html ===
Use [https://raw.githubusercontent.com/pixelb/scripts/master/scripts/ansi2html.sh ansi2html.sh]. It only requires gawk.
# Use wget to download it
# sudo apt-get install gawk
# chmod +x ansi2html.sh
# colordiff file1 file2 | ./ansi2html.sh > diff.html


=== using a the result of a diff in a if statement ===
== Logging memory ==
<pre>
* [[#System_monitor_tools_.28GUI.29 | Linux system monitor tools]] where [http://sebastien.godard.pagesperso-orange.fr/documentation.html Sysstat] package can be used.
ls -lR $dir > a
* [https://www.linux.com/learn/how-much-memory-installed-and-being-used-your-linux-systems How Much Memory Is Installed and Being Used on Your Linux Systems?]
ls -lR $dir > b
* [https://stackoverflow.com/questions/1868210/how-to-log-the-memory-consumption-on-linux How to log the memory consumption on Linux?]
* [https://www.2daygeek.com/linux-commands-check-memory-usage/ 8 Commands to Check Memory Usage on Linux]
* [https://www.binarytides.com/linux-command-check-memory-usage 5 commands to check memory usage on Linux]
** '''free -m''', '''free -h''', ''' watch -n 10 free -m''' (free -s 10 gives an error 'seconds argument `10' failed)
** '''head -3 /proc/meminfo'''
** '''vmstat -s'''
** '''top'''
** '''htop'''


DIFF=$(diff a b)
== Shows Per-Program Memory Usage On Linux ==
if [ "$DIFF" != "" ]  
* '''atop''' command. '''atop -m''' and press p (per program). Look at the 'RSIZE' column.
then
** [https://unix.stackexchange.com/a/209915 Sum the memory usages of all the processes of a program?]
    echo "The directory was modified"
** [https://www.redhat.com/sysadmin/analyzing-linux-server-performance-atop  Analyzing Linux server performance with atop]
fi
** [https://haydenjames.io/use-atop-linux-server-performance-analysis/ atop – For Linux server performance analysis]
</pre>
* [https://unix.stackexchange.com/a/235988 How to view summaric memory usage of groups of commands (instead of processes)]. '''ps -C firefox --no-headers -o pmem'''. The result is one column. It shows the percentage not the actual memory. And it cannot catch some programs like "Web Content" or "WebExtensions" associated with Firefox.
Another example
* '''ps_mem''': https://www.linuxuprising.com/2019/04/psmem-shows-per-program-memory-usage-on.html.
<pre>
{{Pre}}
if [ "$(diff file1.html file2.html)" == "" ]; then echo Same; else echo Different; fi
$ pip install ps_mem
$ ps_mem -p $(pgrep -d, -u $USER)
Private  +  Shared  =  RAM used Program
...
249.9 MiB +  43.9 MiB = 293.9 MiB firefox
549.7 MiB +  82.2 MiB = 631.9 MiB Web Content (6)
  1.0 GiB + 149.6 MiB =   1.2 GiB chrome (16)
---------------------------------
                          3.2 GiB
</pre>
</pre>


=== Listen to pandora in Europe: install squid proxy ===
== Check RAM information ==
http://www.cyberciti.biz/faq/access-pandora-radio-using-proxy-server-outside-usa/
* [https://www.howtogeek.com/792783/how-to-use-the-pmap-command-on-linux/ How to Use the pmap Command on Linux]
 
* [https://www.cyberciti.biz/faq/how-to-find-the-number-of-ram-slots-in-linux/ How to find the number of RAM Slots in Linux] 2021
Interestingly, the firefox connection settings should choose '''HTTP Proxy''' instead of 'SOCKS host'.
* [https://www.binarytides.com/linux-command-check-memory-usage 5 commands to check memory usage on Linux]
{{Pre}}
sudo dmidecode -t memory


=== Bypass blocked website from work computer ===
sudo dmidecode -t 17
* http://www.panix.com/~ruari/censorship.html
* http://www.cyberciti.biz/faq/set-up-ssh-tunneling-on-a-linux-unix-bsd-server-to-bypass-nat/
<pre>
ssh -D 4096 user@remoteip
ssh -D 4096 -p 23 user@remoteip
</pre>
</pre>
This will require you to enter the password and leave you in the remote machine. If a nonstandard port is required, we can use '''-p''' option.


Now in the firefox, we need to go to Edit -> Preferences -> Advanced -> Network tab -> Settings... Check 'Manual proxy configuration' (The default is 'Use system proxy settings') and enter 'localhost' for '''SOCKS Host''' and '4096' for the Port. Don't enter 'localhost' in the HTTP Proxy.
== Free up memory ==
* [https://www.makeuseof.com/improve-performance-free-up-ram-on-linux/ How to Free Up Memory and Improve RAM Performance on Linux]
* [https://linuxtldr.com/clear-buffer-cache-memory-linux/ How to Clear Buffer and Cache Memory in Linux]


On Windows, we can use Putty. In short, in the left-hand panel, navigate through Connection > SSH > Tunnels. Enter 4096 in the '''Source Port''' box and select the '''Dynamic''' radio button. Click Add and “D4096″ will appear in the Forwarded Ports list.  The setting in the firefox end is the same. See also my [http://taichi.asuscomm.com:81/mediawiki/index.php/Windows#Secure_web_access_from_anywhere_using_secure_tunnel Windows] wiki page.
== Monitor Memory Utilization And Send an Email ==
* [https://www.2daygeek.com/linux-bash-script-to-monitor-memory-utilization-usage-and-send-email/ Bash Script to Monitor Memory Usage on Linux]
* [https://www.tecmint.com/shell-script-to-send-email-alert-when-memory-low/ A Shell Script to Send Email Alert When Memory Gets Low]. This uses '''$(free -mt | grep Total | awk '{print $4}')''' to get the available memory.
* [https://www.cloudsavvyit.com/1230/getting-started-with-monit-for-server-monitoring/ Getting Started with Monit for Server Monitoring]


Linux journal also put a video on [http://www.youtube.com/watch?v=fgX04JS-7sA youtube]. We can use http://www.ipligence.com/geolocation to check the current location. The port number is 1080 in the example. The example actually also use '-N' option which means no interaction; i.e. ssh -N -D 1080 user@remoteip. So we won't see anything after we type our password. Once we want to stop SOCK proxy, we just need to hit Ctr+C on terminal.
== zram ==
[https://opensource.com/article/22/11/zram-swap-linux rop swap for zram on Linux]


=== ssh going through one host to reach another server ===
= [https://www.ghacks.net/2017/11/04/5-things-to-do-after-a-fresh-install-of-gnulinux/ Things to do after a fresh install of GNU/Linux] =
http://www.cyberciti.biz/faq/linux-unix-ssh-proxycommand-passing-through-one-host-gateway-server/


Simple method is
# Run upgrade such as '''apt-get update; apt-get upgrade'''. It helps to resolve the unmet dependencies issue too.
<syntaxhighlight lang="bash">
# Increase audio quality
$ ssh -tt vivek@Jumphost ssh -tt vivek@FooServer
# Make sure firewall is enabled.
</syntaxhighlight>
# Disable any unnecessary services
# Install Timeshift
# Install ClamAV / Clamtk antivirus


Another method is to use ssh ProxyCommand to tunnel connections.
= Query whether the OS is 64-bit or 32-bit =
 
<pre>
=== scp ===
SYSTEM_ARCH=getconf LONG_BIT
==== file path with spaces ====
echo $SYSTEM_ARCH
Use double quotes around the full path and the backslash to escape any space.
</pre>
<syntaxhighlight lang="bash">
 
scp user@example.com:"web/tmp/Master\ File\ 18\ 10\ 13.xls" .
= Command line improved =
</syntaxhighlight>
https://remysharp.com/2018/08/23/cli-improved


==== Recursive copying ====
= Directory permission / attribute =
Use '''-r''' parameter.
See http://unix.stackexchange.com/questions/21251/how-do-directory-permissions-in-linux-work


==== Preserve permissions and modes ====
When applying permissions to directories on Linux, the permission bits have different meanings than on regular files.
Use '''-p''' parameter.


==== scp files through one intermediate host ====
* The write bit allows the affected user to create, rename, or delete files within the directory, and modify the directory's attributes
http://stackoverflow.com/questions/9139417/how-to-scp-with-a-second-remote-host
* The read bit allows the affected user to list the files within the directory
* '''The execute bit allows the affected user to enter the directory, and access files and directories inside'''


The following command is tested.
When we create a new directory, the attribute is 775. Some pre-created directories (Desktop, Documents, Music, Pictures, Public) have an attribute 755.
<syntaxhighlight lang="bash">
scp -o 'ProxyCommand ssh user@remote1 nc %h %p' user@remote2:path/to/file .
</syntaxhighlight>


==== scp with non-standard port ====
= Making a new temporary directory =
Use '''-P''' argument.
https://www.howtoforge.com/linux-mktemp-command/
<pre>
{{Pre}}
ssh -P 23 myfile user@remoteip:
mktemp  # temp directory is under /tmp
mktemp -d tempdirXXX # temp directory is under the current directory
mktemp tempfileXXX # temp file under the current directory
</pre>
</pre>


==== scp or ssh without password ====
= Shell =
http://www.thegeekstuff.com/2008/06/perform-ssh-and-scp-without-entering-password-on-openssh/
== Login shell and non-login shell ==
# Verify that local-host and remote-host is running openSSH
Login Shell
# Generate key-pair on the local-host using ssh-keygen
# /etc/profile
# Install public key on the remote-host
# /etc/profile.d/*.sh
# Give appropriate permission to the .ssh directory on the remote-host
# ~/.bash_profile or ~/.profile (for example, environment variable like PATH)
# Login from the local-host to remote-host using the SSH key authentication to verify whether it works properly
# ~/.bashrc
# Start the SSH Agent on local-host to perform ssh and scp without having to enter the passphrase several times
# /etc/bashrc
# Load the private key to the SSH agent on the local-host
# ~/.bashrc
# Perform SSH or SCP to remote-home from local-host without entering the password


Another option is to use '''ssh -i IDENTITY_FILE'''. See [http://superuser.com/questions/399876/scping-using-key-file-as-a-parameter-how-can-i-do-that-if-possible superuser.com].
Non-Login shell
# ~/.bashrc
# /etc/bash.bashrc or /etc/bashrc
# ~/.bashrc (bash-related settings, for example, prompt string, aliases)


=== ssh key ===
Note: Bash only reads the first of the files in ~/ that it finds (and ignore the rest). '''rc''' means ''run commands'' for example, ''.nanorc''.  
SSH key is useful if you want a password-less login to a remote system. Some useful resources:
* https://help.ubuntu.com/community/SSH/OpenSSH/Keys
* https://help.github.com/articles/generating-ssh-keys


The steps are
=== Aliases and Functions for Individual Users ===
* Check if there is an existing key
# /etc/profile (systemwide environment and shell variables)
<syntaxhighlight lang='bash'>
# /etc/profile.d/*.sh (systemwide environment and shell variables)
ls -al ~/.ssh
# ~/.bash_profile (user '''environment and shell variables''')
</syntaxhighlight>
# ~/.bashrc (executes /etc/bashrc)
* Create a new RSA key pair:
# /etc/bashrc (systemwide aliases and shell functions)
<syntaxhighlight lang='bash'>
# ~/.bashrc (user '''aliases''' and shell functions)
ssh-keygen -t rsa
</syntaxhighlight>
* Copy the public key to a remote host ([email protected]) over ssh. The current user (eg brb) and the remote user (eg git)have not any relationship (they most likely have different user names):
<syntaxhighlight lang='bash'>
ssh-copy-id [email protected] # this will 'append' the key to the remote-host’s .ssh/authorized_key.
</syntaxhighlight>
Or
<syntaxhighlight lang='bash'>
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"
</syntaxhighlight>
* Delete the authorized key. Open the text file '.ssh/authorized_keys' and remove the offending lines.
* Test if this is working by trying 'ssh git@123.45.56.78'.
* To disable the password for root login. Type ''sudo nano /etc/ssh/sshd_config''
<pre>
PermitRootLogin without-password
</pre>
Then run the following to put the changes into effect:
<syntaxhighlight lang='bash'>
reload ssh
# Or service ssh restart
</syntaxhighlight>
If we like to ask all users to use key-based to log in, we can modify the line
<pre>
PasswordAuthentication no
</pre>
in sshd_config.


==== Multiple ssh keys ====
=== Why does it take tens of seconds to get a shell prompt? ===
If we want to use a specific key in ssh, use
https://serverfault.com/a/722496 If your profile or bashrc have expensive things, consider trimming them back.
<syntaxhighlight lang='bash'>
ssh -i ~/.ssh/xxx_id_rsa [email protected]
</syntaxhighlight>
See also '''ssh-add''' & '''ssh-agent'''.
* https://confluence.atlassian.com/pages/viewpage.action?pageId=271943168
* http://askubuntu.com/questions/269140/how-to-use-multiple-ssh-keys-with-different-accounts-and-hosts


==== ssh key management ====
On raspbian commenting out some lines does help. Interestingly, the same lines does not make any difference on x86 server.
* Using [https://www.howtoforge.com/tutorial/ssh-key-management-with-privacyidea/ privacyIDEA] (howtoforge.com).


==== Copy ssh keys to another computer ====
== the source command ==
http://askubuntu.com/questions/134975/copy-ssh-private-keys-to-another-computer
The . is a shorthand for the '''source''' command in bash. <syntaxhighlight lang="sh" inline>source ~/.bashrc</syntaxhighlight> and <syntaxhighlight lang="sh" inline>. ~/.bashrc</syntaxhighlight> are equivalent.


<syntaxhighlight lang='bash'>
== login shell (.bash_profile) vs interactive shell (.bashrc) ==
$ chown brb:brb ~/.ssh/id_rsa*
* http://stackoverflow.com/questions/18186929/differences-between-login-shell-and-interactive-shell
$ chmod 600 ~/.ssh/id_rsa
* [https://linuxtldr.com/interactive-login-and-non-login-shell/ What is Interactive Login and Non-Login Shell]
$ chmod 644 ~/.ssh/id_rsa.pub
* http://serverfault.com/questions/8882/what-is-the-difference-between-a-login-and-an-interactive-bash-shell
</syntaxhighlight>


If we do not change the permission correctly in <id_rsa>, we will get a warning: Unprotected private key file. Permissions 0664 for '/home/USERNAME/.ssh/id_rsa' are too open.
# '''login shell''' - non desktop environment. ~/''.bash_profile'' is sourced for the bash shell. It is the shell you get when logging in or opening a new terminal session.
#* [https://askubuntu.com/a/969923 You do not usually have .bash_profile on Ubuntu, nor should you usually create that file.]
#* On new Ubuntu, there is no .bash_profile. It has '''.profile'''.
#* you should not put aliases in '''.profile''' at all, nor is ''.bash_profile'' a good place for them because you will want your aliases to work in interactive shells whether or not they are login shells.
#* Login shells are interactive shells.
# '''interactive shell''' - Ctrl+Alt+t to open a terminal from a graphical mode (desktop environment) and also the [https://unix.stackexchange.com/a/46856 ssh connection].  ~/'''.bashrc''' is source. We usually edit ~/.bashrc to set up the environment to include fancy prompt, set aliases, set history options, or define custom shell functions. [https://www.cyberciti.biz/faq/linux-unix-bash-check-interactive-shell/ Bash Check If Shell Is Interactive or Not Under Linux / Unix Oses]
# '''Non-interactive shell''' - instances of the shell you can't use interactively. Shells that are started to run a command or script.


==== Preserve ssh keys when upgrading computers ====
To determine the shell type: '''echo $-'''  
* An article from [http://www.bsdnewsletter.com/bsda-book/Preserve_existing_SSH_host_keys_during_a_system_upgrade.html bsdnewsletter.com].
<syntaxhighlight lang='bash'>
ls -l /etc/ssh/*key* > ~/key_list
mkdir ~/serverkeys && cp -p /etc/ssh/*key* ~/serverkeys/
cp -p ~/serverkeys/*key* /etc/ssh
ls -l /etc/ssh/*key* | diff - ~/key_list
</syntaxhighlight>
If diff produces no output, you're finished.


==== Disable SSH host key checking ====
export environment variables
<syntaxhighlight lang='bash'>
# Both a '''login shell and an interactive one'''. SSH (Putty) to connect to a remote machine.
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no [email protected].100
# When a shell runs a script or a command passed on its command line, it's a '''non-interactive, non-login shell'''.
</syntaxhighlight>


To disable the checking for all hosts, in your '''~/.ssh/config''' (if this file doesn't exist, just create it):
=== /root/.bashrc ===
<pre>
If we use "sudo SOME_COMMAND", ''~/.bashrc'' won't work. In this case, we have to
Host *
# run "sudo su"
    StrictHostKeyChecking no
# Edit '''/root/.bashrc'''
</pre>


==== Handling the ssh key change when connecting to a remote machine ====
== Login banner ==
An article from [http://www.cyberciti.biz/faq/warning-remote-host-identification-has-changed-error-and-solution/ cybercitz.biz].
[https://kerneltalks.com/tips-tricks/how-to-configure-login-banners-in-linux/ How to configure login banners in Linux (RedHat, Ubuntu, CentOS, Fedora)]. '''/etc/motd''' and '''/etc/login.warn'''


* Method 1. Remove the key using '''ssh-keygen -R''' command.
== Change to root shell ==
<syntaxhighlight lang='bash'>
The following command will switch to an environment similar to what the user would expect had the user logged in directly.  
$ ssh-keygen -R {server.name.com}
{{Pre}}
$ ssh-keygen -R {ssh.server.ip.address}
sudo su -
$ ssh-keygen -R server.example.com
# OR
</syntaxhighlight>
sudo su
* Method 2. Add correct host key in /home/user/.ssh/known_hosts
# OR
* Method 3. Just delete the known_hosts file If you have only used one ssh server
sudo -s
</pre>
This can be useful when running 'su' or 'su -' failed because of an authentication failure error (note Ubuntu locked the root account).
 
See also
* [https://wiki.archlinux.org/index.php/su wiki.archlinux.org].
* Difference of 'su', 'sudo -s' and 'sudo -i' from [http://askubuntu.com/questions/70534/difference-between-su-sudo-s-sudo-i askubuntu.com]. [http://askubuntu.com/questions/64178/why-is-sudo-s-better-than-sudo-su 'sudo -s' and 'sudo su'?]
 
For sudo to work, my account ('debian' in this case) has to be included in the config file '''/etc/sudoers'''.
{{Pre}}
debian  ALL=NOPASSWD: ALL
</pre>
When sudo is invoked, it asks for the password of the user who started it.


=== Running commands on a remote host with SSH ===
== pinky: find out about the people logged on to your Linux computer ==
<syntaxhighlight lang='bash'>
[https://www.howtogeek.com/427004/how-to-use-the-pinky-command-on-linux/ How to Use the pinky Command on Linux]
ssh user@host 'COMMANDS'


ssh user@host "command1; command2; command3"
== su: Switch to another user and run a command ==
<ul>
<li>su means 'substitute user'.
<li>Use
<pre>
su newusername  # keeps the environment variables of the original user
su - newusername # clears all the environment variables
</pre>
<li>[https://www.cyberciti.biz/open-source/command-line-hacks/linux-run-command-as-different-user/ Linux Run Command As Another User]
'''runuser -l''' command
{{Pre}}
runuser -l  userNameHere -c 'command'
</pre>
</ul>


COMMANDS="command1; command2; command3"
== Keyboard shortcut to move cursor in the terminal ==
ssh user@host "$COMMANDS"
* Alt + b: go left (back) one word
</syntaxhighlight>
* Alt + f: go forward on word


A practical example
Example: cd ~/bitbucket/gbmpdx/annovar_biowulf  (Now press Alt+b to see the cursor moves)
<syntaxhighlight lang='bash'>
#!/bin/bash


IP_LIST="192.168.0.1 192.168.0.5 192.168.0.9"
== Record terminal session to a text file ==
USER="test"
<pre>
script history_log.txt
# recording begins
exit # stop recording
</pre>
This will include everything showing on your screen.


for IP in $IP_LIST;
== Tools To Record Your Terminal And Generate Animated Gif or SVG Images ==
do
=== Asciinema & agg ===
  utime=$(ssh ${USER}@${IP} uptime | awk '{ print $3 }' )
* It works on Ubuntu 23.04
  echo $IP uptime:  $utime
* [https://github.com/asciinema/asciinema Asciinema]
done
** [https://www.2daygeek.com/linux-asciinema-record-your-terminal-sessions-share-them-on-web/ Asciinema – Record and Share your terminal sessions on the fly]
</syntaxhighlight>
* [https://www.omgubuntu.co.uk/2023/04/pip-install-error-externally-managed-environment-fix 3 Ways to Solve Pip Install Error on Ubuntu 23.04]
* https://github.com/asciinema/agg
<pre>
$ # sudo pip3 install asciinema # Error
$ # sudo apt install python3-asciinema # Error
$ sudo apt install pipx
$ pipx ensurepath
Success! Added /home/brb/.local/bin to the PATH environment variable.


=== ssh log files ===
Consider adding shell completions for pipx. Run 'pipx completions' for
* /var/log/syslog
instructions.
* /var/log/auth.log  (see who is trying to connect; check out http://ip-lookup.net/index.php to see their geolocation)


It is also helpful to check /etc/hosts.allow and /etc/hosts.deny for any possible wrong configuration.
You will need to open a new terminal or re-login for the PATH changes to take
effect.


=== Graphical way to display disk usage ===
Otherwise pipx is ready to go!
* http://www.makeuseof.com/tag/how-to-analyze-your-disk-usage-pattern-in-linux/
</pre>
For example, to use xdiskusage, we run '''apt-get install xdiskusage''' and launch it by '''xdiskusage ~/'''.
Open another tab
* Ubuntu has a built-in program called "Disk Usage Analyzer". Just search it from Dash. Looks useful!
<pre>
pipx install asciinema
asciinema rec 2g-test
asciinema play 2g-test
chmod +x Downloads/agg-x86_64-unknown-linux-gnu
Downloads/agg-x86_64-unknown-linux-gnu 2g-test 2g-test.gif
open 2g-test.gif
</pre>


=== Display files sorted by modified date in a directory recursively ===
=== terminalizer ===
* [http://stackoverflow.com/questions/5566310/how-to-recursively-find-and-list-the-latest-modified-files-in-a-directory-with-s stackoverflow.com]  
* https://github.com/faressoft/terminalizer
<syntaxhighlight lang='bash'>
** [https://www.2daygeek.com/terminalizer-a-tool-to-record-your-terminal-and-generate-animated-gif-images/ Terminalizer – A Tool To Record Your Terminal And Generate Animated Gif Images]
stat --printf="%y %n\n" $(ls -tr $(find DIRNAME -type f))
** [https://itslinuxfoss.com/install-npm-ubuntu-22-04/ How to Install NPM in Ubuntu 22.04?]
** Ubuntu
::<syntaxhighlight lang='bash'>
sudo apt update
sudo apt install nodejs npm
sudo npm install -g npm
sudo npm install -g terminalizer
terminalizer record demo
terminalizer play demo
terminalizer render demo
# https://github.com/faressoft/terminalizer/issues/29
# https://github.com/faressoft/terminalizer/issues/211
</syntaxhighlight>
</syntaxhighlight>
* [http://superuser.com/questions/416308/list-files-recursively-and-sort-by-modification-time superuser.com]
<syntaxhighlight lang='bash'>
find -type f -printf '%T+\t%p\n' | sort -n
</syntaxhighlight>
Both of methods give the same output. Note the latest changed file is shown at the bottom of the output.


=== Sort files by their size ===
=== Termtosvg ===
use the '-S' option.
(archived) [https://www.2daygeek.com/termtosvg-record-your-terminal-sessions-as-svg-animations-in-linux/# Termtosvg – Record Your Terminal Sessions As SVG Animations In Linux]
<syntaxhighlight lang='bash'>
 
ls -lS
== Record and Replay Linux Terminal Sessions Activity: script ==
</syntaxhighlight>
[https://www.linuxtechi.com/record-replay-linux-terminal-sessions-activity/ Learn how to Record and Replay Linux Terminal Sessions Activity]
 
== Recording your terminal: asciinema ==
https://asciinema.org/
 
== Clear screen ==
ctrl + l


=== df: Display disk space ===
== Clear text ==
<syntaxhighlight lang='bash'>
ctrl + u: "deletes" all the entered text to the left of the cursor. Does not work in macOS shell but R console from RStudio in macOS still works.
df -h
df -h -T  # show the 't'ype of the file system
df -h -t ext4 # show file systems of given type (ext4 in this example)
df -a    # show all file system (include ones that have a size of zero blocks)
</syntaxhighlight>


=== du: Display directory size with sorting and human readable ===
= Redirect standard error =
Use [http://www.cyberciti.biz/faq/unix-disk-usage-command-examples/ ncdu] program (more interactive). Although it is a command line program, we can use the mouse to move through each directory to see its sub-directories.
http://bash.cyberciti.biz/guide/Standard_error. Use '''2>''' operator.
<pre>
<pre>
sudo apt-get install ncdu
command 2> errors.txt
ncdu
</pre>
</pre>


* http://www.cyberciti.biz/faq/linux-check-disk-space-command/
== Redirect standard output ==
And the ''du'' method.
This can be used in the cron job or displaying a clock on the desktop.
<pre>
<pre>
du -h ~/ --max-depth=1
$ cat ~/bin/clock
du -h ~/ --max-depth=1 --exclude ".*" | sort -nr | cut -f2 | xargs -d '\n' du -sh
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139  &>/dev/null &
du -a -h ~/ # kilobytes will be used, '-a' is to see all files, not just directories.
du -a ~/ | sort -nr | head -n 10  # sort from the largest file size first
</pre>
</pre>
The --exclude is to hide hidden directories, '-n' is to compare according to string numerical value, and '-r' is to reverse the result.


Note that the 'du' commands may be cheating. See the following screenshot.
= Quotes and asterisk =
Combining these two will not work. For example
{{Pre}}
brb@T3600 ~ $ ls -l ~/GSE48215/*.fastq
-rw-r--r-- 1 brb brb 16226673016 Jun 14 14:13 /home/brb/GSE48215/SRR925751_1.fastq
-rw-r--r-- 1 brb brb 16226673016 Jun 14 14:13 /home/brb/GSE48215/SRR925751_2.fastq
brb@T3600 ~ $ ls -l '~/GSE48215/*.fastq'
ls: cannot access ~/GSE48215/*.fastq: No such file or directory
brb@T3600 ~ $ ls -l "~/GSE48215/*.fastq"
ls: cannot access ~/GSE48215/*.fastq: No such file or directory
</pre>


[[File:DiskUsage.png|100px]]
= cat command alternatives =
* [https://github.com/sharkdp/bat/releases bat]
* [https://computingforgeeks.com/bat-cat-command-with-syntax-highlighting-and-git-integration/ Bat – Linux cat command with syntax highlighting and Git integration]
* Direct installing bat using 'apt install' does not work:( Grab the binary from github works.
{{Pre}}
$ curl -s  https://api.github.com/repos/sharkdp/bat/releases/latest |grep browser_download_url |  cut -d '"' -f 4 | grep 'amd64.deb' | grep -v musl | wget -i -
$ sudo dpkg -i bat_*_amd64.deb
</pre>


The discrepancy is explained by 'sector'. See http://askubuntu.com/questions/122091/difference-between-filesize-and-size-on-disk.
= ls command =
List Files With Detailed Information from [https://www.makeuseof.com/ls-command-linux/ How to Use the ls Command in Linux]


To use UID/GID instead of the user name and group name in '''ls -l''', use the '''-n''' option.
<pre>
ls -n
</pre>
To make a pretty output by showing selected columns (col 9 is the file name and col 5 is the file size)
<pre>
<pre>
$ sudo dumpe2fs /dev/sda1 | grep -i "block size"
$ ls -nt bad | grep -v ^total | awk '{ printf  "%-20s %15i\n", $9, $5}'
dumpe2fs 1.41.14 (22-Dec-2010)
recal.bai                    8069704
Block size:              4096
recal.bam                12275091222
recal_data.table            1012453
realigned_reads.bai          8065496
</pre>
</pre>


To show a file size in terms of blocks, we can use
== Follow the symbolic link ==
Use '''-H''' option
{{Pre}}
ls -lH myDir
</pre>
 
== List only directories ==
<pre>
<pre>
ls -s
ls -d */              # current directory
ls -ld ~/Downloads/*/  # ~/Downloads
ls -l -d */
</pre>
</pre>
So for example, if a file takes 150 blocks, and if a block takes 4096 bytes, then the file takes 150*4096/1024 KB on disk.


=== Apache benchmark (ab) testing ===
== List only files ==
<pre>
<pre>
ab -n 100 -c 10 http://taichi.selfip.net:81/
ls -l | egrep -v '^d'
ab -n 100 -c 10 http://taichi.selfip.org/
</pre>
</pre>
* http://www.petefreitag.com/item/689.cfm
* http://en.wikipedia.org/wiki/ApacheBench


=== rsync ===
== Find and Delete Broken Symbolic Links ==
==== rsync with exclude files/directories ====
See http://www.thegeekstuff.com/2011/01/rsync-exclude-files-and-folders/. The key is excluded files are relative to the current directory even we specify the absolute path. For example /path1/path2/file does not mean the file is located under /path1/path2; it means the file is located under ./path1/path2.
<pre>
<pre>
rsync -avz --exclude '/path1/path2/file' source/ destination/
find /path/to/directory -xtype l -delete
</pre>
</pre>


==== rsync to exclude hidden files/directories ====
== Special characters, escape ==
<syntaxhighlight lang='bash'>
[https://stackoverflow.com/a/19177228 List of characters which needs to be escaped in a linux shell command]
--exclude=".*# exclude both hidden files and directories
 
--exclude ".*"  # same as above
<pre>
|  &  ;  <  >  (  )  $  `  \  '  <space>  <tab>  <newline>
</pre>


--exclude ".*/" # exclude hidden directories ONLY
Opened MS-Office documents' filenames start with "~$". <u>The dollar sign character has to be escaped</u>; eg ''' ls -l ~\$* ''' to list these kind of files or '''rm ~\$*''' to delete these files.


--exclude ".git" # exclude .git directory ONLY; relative to the directory to be synchronized.
== Check non-English characters ==
</syntaxhighlight>
[https://www.baeldung.com/linux/find-non-ascii-chars How to Find Non-ASCII Characters in Text Files in Linux]
<pre>
perl -ne 'print if /[^[:ascii:]]/' sample.txt
</pre>


==== rsync with -a option ====
== ls | more without lose color ==
The '''-a''' flag in there stands for “archive,” and it’s important to include. It makes sure that the sync command is recursive (meaning any sub-folders and files inside of old_movies are copied too) and it’s important for preserving all of those modification dates, symbolic links, permissions, and other goodies we talked about earlier.
{{Pre}}
$ ls --color=auto
$ ls --color | more
</pre>
Most likely your ls is aliased to ls --color=auto. If you do ls --color (which is morally equivalent to ls --color=always), that will force it to turn on colors.


==== rsync with non-standard port ====
== ls directories color ==
Use '''-e''' option
[https://www.howtogeek.com/307899/how-to-change-the-colors-of-directories-and-files-in-the-ls-command/ How to Change the Colors of Directories and Files in the ls Command]. No need to use the export command when we want to add it to .bashrc file.
<pre>
<pre>
rsync -avz -e "ssh -p 23" mydir user@remoteip:
# orange color
export LS_COLORS=$LS_COLORS:'di=0;33:'
# OR yellow color if your terminal supports 256 colors
export LS_COLORS=$LS_COLORS:'di=38;5;226:'
</pre>
</pre>


==== rsync with progress bar ====
== ls output with color background ==
Use '''--progress''' option.
[http://unix.stackexchange.com/questions/94498/what-causes-this-green-background-in-ls-output stackexchange] or [http://askubuntu.com/questions/17299/what-do-the-different-colors-mean-in-the-terminal askubuntu].
 
In my case, after I apply '''chmod 755 -R XXXX''', the weird green background color goes away.
 
== ls output without user/group columns ==
https://unix.stackexchange.com/a/205165
<pre>
ls -lhog
</pre>
To further skip the first 2 columns (the permissions and link count) we can use
<pre>
<pre>
rsync -avz --progress file1 file2
ls -lhog | sed 's/^[^ ][^ ]*  *[^ ][^ ]* //'
# total 95G
#  51G May  7 11:37 SRR10156301_3.fastq  --> file
#  23G May  7 11:35 SRR10156301_2.fastq  --> file
#  18G May  7 11:35 SRR10156301_1.fastq  --> file
# 4.0K May  7 11:24 SRR10156301          --> directory
</pre>
</pre>
The 'rsync' command works on transferring files local to local too.


Or it is better to use '''-P''' option which is the same as '''--partial --progress'''. When it is used you’ll get a progress dialog at the command line that shows you which file is currently transferring, what percentage of that transfer is complete, and how many more files are left to check. As each file completes, you’ll see an ever-growing list of completed file transfers, which is great for making sure everything transfers successfully. It also allows you to easily resume suspended or interrupted transfers. Combined, you can see how it’ll show you which file was the last one to go, where it failed, and if it failed, give you the option to resume. It’s a pretty powerful combination.
== ls output selected columns ==
The following example will sort the output by file size and output only the file size and file name columns.
{{Pre}}
ls -lS  . | awk '{print $5 "\t" $9}'
 
ls -lhS  . | awk '{print $5 "\t" $9}'
 
# Mac
ls -lS  *.Rmd |head | awk '{print $6 "\t" $10}'
# a range of columns:
ls -lS  *.Rmd |head | awk -v f=6 -v t=10 \
    '{for(i=f;i<=t;i++) printf("%s%s",$i,(i==t)?"\n":OFS)}'
</pre>


==== rsync on Windows ====
== ls suddenly wrapping items with spaces in single quotes ==
Download and install command line rsync from http://www.rsync.net/resources/howto/windows_rsync.html. The website also provides a documentation. Some people are concern about the license issue. The website [https://www.itefix.no/i2/content/cwrsync-free-edition here] provides a link to the free, old but usable version 4.0.5 which is newer than I tested v3.1.0.
Use '''ls -N''' to remove single quotes for files containing spaces. See [https://unix.stackexchange.com/a/258687 Why is 'ls' suddenly wrapping items with spaces in single quotes?]


Below are my note by using cwrsync v3.1.0 installer got from http://www.rsync.net.
Better to add '''export QUOTING_STYLE=literal ''' to .bashrc
<pre>
cd C:\Program Files (x86)\cwRsync\bin
ssh-keygen -t rsa -N ''
rsync -av "/cygdrive/c/Users/brb/.ssh/id_rsa.pub" [email protected]:.ssh/authorized_keys


rsync -av "/cygdrive/c/Users/brb/Downloads/cytokineMC.txt" [email protected]:Downloads/
== ls on BSD/macOS ==
Use the '''-G''' option to get a color output
{{Pre}}
$ ls -G
</pre>
</pre>


=== Filezilla ===
== realpath ==
[https://wiki.filezilla-project.org/Keyboard_shortcuts Keyboard shortcut]. Especially, Alt+Down=Transfers the currently selected item to an item of the same name in the other pane.
'''realpath FILENAME''' to get the full path of a file.
=== The device is busy ===
 
* http://oletange.blogspot.com/2012/04/umount-device-is-busy-why.html
= tree command =
<pre>
'''tree -d''': show directories only
brb@brb-P45T-A:~$ sudo umount /media/brb/TOSHIBA
 
[sudo] password for brb:
== tre command ==
umount: /media/brb/TOSHIBA: device is busy.
* [https://github.com/dduan/tre github]. Binary files for x86 and arm linux are available. To use it, run "tre DIRECTORYNAME" or "tre" to list files recursively from the current directory.
        (In some cases useful info about processes that use
 
        the device is found by lsof(8) or fuser(1))
= cp command =
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
[https://www.howtoforge.com/linux-cp-command/ Linux cp command tutorial for beginners (8 examples)]
umount: /media/brb/TOSHIBA: device is busy.
 
        (In some cases useful info about processes that use
== copy a directory ==
        the device is found by lsof(8) or fuser(1))
{{Pre}}
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
cp -avr Dir1 Dir2
COMMAND  PID USER  FD  TYPE DEVICE  SIZE/OFF NODE NAME
VBoxSVC 5600  brb  18w  REG  8,33 4294967295    3 /media/brb/TOSHIBA/Windows 10.ova (deleted)
brb@brb-P45T-A:~$ kill -9 5600
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
brb@brb-P45T-A:~$
</pre>
</pre>
where -a will preserve the attributes of files/directories, -v means verbally and -r means copy the directory recursively.
= Copy a file with progress bar with '''pv''' (plus how to eject the USB drive) =
http://www.tecmint.com/monitor-copy-backup-tar-progress-in-linux-using-pv-command/


* See http://ocaoimh.ie/2008/02/13/how-to-umount-when-the-device-is-busy/
{{Pre}}
<pre>
sudo apt-get install pv
# fuser -m /dev/sdc1
pv file1 > file2    # don't forget the ">" operator and the destination is a file, not a directory
/dev/sdc1: 538
# ps auxw|grep 538
donncha 538 0.4 2.7 219212 56792 ? SLl Feb11 11:25 rhythmbox
</pre>
</pre>
Another handy one is:
 
<pre>
After that, instead of clicking the reject icon from the file manager to eject it, it is better to use a [http://stackoverflow.com/questions/13224509/linux-ubuntu-safely-remove-usb-flash-disk-via-command-line command line] to do that because there is no expect time for users to know when it will take for finish writing the data to a USB drive.
umount -l /dev/sdwhatever
{{Pre}}
sudo apt-get install udisks
 
sudo udisks --unmount /dev/sdb1  # /dev/sdb1 is the partition
sudo udisks --detach /dev/sdb    # /dev/sdb is the device
</pre>
</pre>


=== Kill a process ===
My testing shows this procedure works (tested by running '''md5sum''' after eject/plug-in) when I need to copy a 9GB file.
<pre>
 
# find the PID
== Reliable way: Split the large file and copy smaller chunks ==
pgrep ProgramName
{{Pre}}
# Kill the ProgramName process
# Use 'sudo iotop -o' to monitor the I/O
kill -9 PID
split -b 4G inputFile  # create xaa, xab, ... files
cat x* > outputFile    # merge them. md5sum check succeeds
 
type  x* > outputFile  # Windows OS. # https://stackoverflow.com/a/60254
 
# Use Prefix, and use numeric suffixes starting from 0
split -b 4M -d inputFile inputFile.part
md5sum inputFile
cat inputFile.part* > inputFile2
ech "LONG_MD5_SUM_From_inputFile inputFile2" | md5sum -c
</pre>
</pre>
It is interesting copying smaller files (eg 4GB) to USB drives is quite stable (just use the '''cp''' command). Even for a not-too large file (6.7GB), pv step looks OK but the unmount/detach step failed.
For a 6.7GB file, it will split it into a 4GB and 2.7GB files. Merge takes longer time if it is done on the USB drive. That is, it is best to do merge in the final destination (internal disk/storage).
* split in the internal hdd: 1min 38sec
* merge in the internal hdd: 37sec
* merge in the USB 3.0 drive: 2min 17sec
Remember: Use a reliable USB drives.
== The operation could not be completed because the volume is dirty ==
On a USB 2.0 drive, I can copy files to there but the drive cannot be rejected (Ubuntu has a pop-up showing it is still writing data to it).
When I forcibly rejects the drive and plug it in a Windows PC, Windows shows the message ''The operation could not be completed because the volume is dirty''. [http://www.infolet.org/2012/10/how-to-solve-error-0x80071AC3-operation-could-not-be-completed-volume-is-dirty.html This] gives a way to run '''chkdsk''' (check and repair a file system).
# Open a Windows File Manager
# Right click the USB drive
# Properties
# Tools -> Check now... Start
Done. Now I can use the drive again.
The Linux equivalent to '''chkdsk''' is '''fsck'''. fsck is a front end that calls the appropriate tool (fsck.ex2, fsck.ex3, e2fsck, ...) for the filesystem in question.
{{Pre}}
umount /dev/sdb1        # thumb drive
sudo fsck /dev/sdb1


=== Create an ext3 file system on a USB flash drive ===
sudo fsck -a /dev/sdb1 # auto repair
<pre>
umount /dev/sdb1  (depending on the device of course)
sudo mkfs.ext3 /dev/sdb1
sudo e2label /dev/sdb1 usbdrive  (change the label)
</pre>
</pre>
We can create MS-DOS file system by
 
For the root disk, you have to use a [https://askubuntu.com/questions/58601/fsck-gets-mad-when-the-file-system-is-mounted live CD]. Otherwise, you will see a message like
<pre>
<pre>
sudo mkfs.vfat /dev/sdb1
$ fsck /dev/sdb1
fsck from util-linux 2.20.1
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdb1 is mounted.
 
WARNING!!!  The filesystem is mounted.  If you continue you ***WILL***
cause ***SEVERE*** filesystem damage.
 
Do you really want to continue<n>? no
</pre>
</pre>


=== Port forwarding ===
= Files =
* https://toic.org/blog/2009/reverse-ssh-port-forwarding/
== List files by sorting according to the file size ==
Use the '''-S''' option in ls.


For example, we like to use source port number 8080, destination port 80 (the http port), and destination server www.ubuntuforums.org.
== List files using wildcard without showing files under subdirectories ==
<pre>
Use the '''-d''' option in ls. For example, the following command will not showing files under R-3.4.4 and R-3.5.3
ssh -L 8080:www.ubuntuforums.org:80 <host>
{{Pre}}
$ ls -d R*
drwxr-xr-x 15 brb brb    4096 Mar 14 09:48 R-3.4.4
-rw-rw-r--  1 brb brb 30474612 Mar 15  2018 R-3.4.4.tar.gz
drwxr-xr-x 15 brb brb    4096 Mar 14 09:31 R-3.5.3
-rw-rw-r--  1 brb brb 30205979 Mar 11 04:04 R-3.5.3.tar.gz
</pre>
</pre>
Where <host> should be replaced by the name of your laptop. The -L option specifies local port forwarding. For the duration of the SSH session, pointing your browser at http://localhost:8080/ would send you to http://www.ubuntuforums.org/.


To stop the ssh session, use ps -ef to find the process id and kill it.
== Delete multiple files ==
[http://www.howtogeek.com/276516/how-to-remove-multiple-subdirectories-with-one-linux-command/ How to Remove Multiple Subdirectories with One Linux Command]
{{Pre}}
rm -r ~/Documents/htg/{done,ideas,notes}
</pre>


==== Reverse port forwarding ====
== Delete a certain type of files recursively under a directory ==
This is most useful in situations where you have a machine which isn't publicly accessible from the internet, but you want others to be able to access a service on this machine. In this case, if you have SSH access to a remote machine which is publicly accessible on the internet, you can set up a reverse port forward on that remote machine to the local machine which is running the service.
For example to delete *.o files under the current directory,
{{Pre}}
find . -type f -name '*.o' -delete
</pre>


<syntaxhighlight lang='bash'>
== Remove all files/directories except for one file/some file type ==
ssh -R 8000:localhost:80 user@REMOTE_MACHINE
https://unix.stackexchange.com/a/153863
</syntaxhighlight>
<pre>
This will forward port 8000 on the remote machine to port 80 on the local machine. Using this method, if you browse to http://localhost on the remote machine, you will actually connected to a web server running on port 8000 of the local machine.
# recursively, including hidden ones
find . ! -name 'file.txt' -type f -exec rm -f {} +


=== Add a new user with home directory ===
# Non-recursively
<pre>
find . -maxdepth 1 ! -name 'file.txt' -type f -exec rm -f {} +
adduser xxx
</pre>
</pre>
find: warning: you have specified the -maxdepth option after a non-option argument !, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.


'''adduser''' is better than '''useradd''' since useradd does not create home directory and it does not even ask the password for new user. '''adduser''' will interactively ask user information.
== Remove all hidden files/directories ==
 
[https://www.cyberciti.biz/faq/bash-linux-unix-delete-hidden-files-directories-command/ Bash Find And Delete All Hidden Files Directories]
To delete the user and home directory, use
<pre>
<pre>
deluser --remove-home xxx
rm -rf .??*  # tested, http://labtestproject.com/linuxcmd/rm.html
</pre>


=== Compress a folder without full path name ===
# list all hidden files/directories
Suppose we want to compress the folder ~/Documents and its subfolders. We want to include Documents folder name but not /home/brb/Documents name.
find . -name ".*" -print
<syntaxhighlight lang="bash">
# Method 1. Include 'Documents' as the top folder name
cd ~/
tar -czvf tmp.tar.gz Documents
# Method 2. Mind the last dot. Not include 'Documents' as the top folder.
tar -czvf tmp.tar.gz -C /home/brb/Documents .


# Double check the tarball
# delete all hidden files
tar -tzvf tmp.tar.gz 
find . -name ".*" -type f -delete
</syntaxhighlight>


=== squashfs ===
find . -name ".DS_Store" -delete
'''squashfs''' is a heavy-compression based read-only filesystem that is capable of compressing 2 to 3 GB of data onto a 700MB. Linux liveCD are built using squashfs. These CDs make use of a read-only compressed filesystem which keeps the root filesystem on a compressed file. It can be loopback mounted and loads a complete Linux env. Thus when some file are required by processes, they are decompressed and loaded onto the RAM and used.
</pre>


* https://en.wikipedia.org/wiki/SquashFS
== Create a new directory and cd to it ==
* http://squashfs.sourceforge.net/
[http://www.howtogeek.com/273304/how-to-make-a-new-directory-and-change-to-it-with-a-single-command-in-linux/ How to Make a New Directory and Change to It with a Single Command in Linux]
* http://elinux.org/Squash_FS_Howto


<syntaxhighlight lang="bash">
== Set permissions for new files or directories ==
# create a squashfs file
* umask: user file-creation mode mask
sudo mksquashfs /etc test.squashfs
* With '''umask 007''', ''newly created files and directories will have all permissions (read, write, and execute) for the user and the group, but no permissions for others''. This is a good practice when you want to share data with other users in the same group but want to completely exclude users who are not group members.
* Set up default umask on Linux: adding the command ''umask 007'' to the '''.bashrc''' file sets the default umask value for your shell. This means that every time you start a new shell session, the umask will be set to 007.
* How it works:
** The default permissions for files are 666 (read and write for owner, group, and others) and for directories are 777 (read, write, and execute for owner, group, and others).
** The default permissions for files are 666 and for directories are 777. In binary, these are 110 110 110 and 111 111 111 respectively. The umask value 007 is 000 000 111 in binary.
** The AND operation is performed between the binary representations of the default permissions and the bitwise '''NOT of the umask value'''. That is, the mask is '''negated''' (its bitwise compliment is taken) and this value is then applied to the default permissions using a logical AND operation.
** The result of the AND operation is 110 110 000 for files and 111 111 000 for directories. In decimal, these are 660 and 770 respectively.
* See [https://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html What is Umask and How To Setup Default umask Under Linux?], [https://www.computerhope.com/unix/uumask.htm Linux umask command].


# mount the squashfs file
== chown and chmod recursively (-R) ==
mkdir /mnt/squash
Use '''-R''' (capital R).
mount -o loop compressedfs.squashfs /mnt/squash
<pre>
# you can acess the contents at /mnt/squashfs
chmod -R u=rwx,go=rx /var/www/html
</pre>
Note it is better not to remove 'x' on folders. Otherwise we will lose the permission to change file attributes for any file under the folder.


# exclude files
Note "chmod -R ugo+rwx XXX" is the same as "chmod -R 777 XXX" b/c "u" stands for user, "g" stands for group and "o" stands for others.
sudo mksquashfs /etc test.squashfs -e /etc/passwd /etc/shadow
# or specify a list of exclude files given in a file
cat excludelist  # /etc/passwd
sudo mksquashfs /etc test.squashfs -ef excludelist
</syntaxhighlight>


=== List contents of tar.gz ===
== Get the chmod numerical value for a file/directory ==
https://unix.stackexchange.com/a/46921
<pre>
<pre>
tar -tzvf myfile.tar.gz
# BSD/OS X:
stat -f "%OLp" <file>
 
# Linux:
stat --format '%a' <file>
stat -c %a <file>
</pre>
</pre>
After that we can use '''ls -lhog''' to verify.


=== Extract files ===
== Files under a directory have question mark attribute  ==
==== Extract .xz file ====
Use '''sudo chmod -R a+x /some/directory''' to fix. This happened when I unzip a zip file compressed in a Windows OS.
<syntaxhighlight lang="bash">
xz -d archive.xz
</syntaxhighlight>


==== Extract tar.xz file ====
== Files have an integer owner in attributes ==
The bottomline is we don't need the 'z' parameter (used for [https://en.wikipedia.org/wiki/Gzip gz] ONLY but does not work for [https://en.wikipedia.org/wiki/Xz xz file])  in the tar command for tar.xz files. And the method also works for tar.gz files. The argument '-f' means the archive file. Recall that the '''tar''' command can be used to store and extract files, so no default parameters.
[https://unix.stackexchange.com/a/13110 What does the “number” in the owner field of files signify in linux?]


<syntaxhighlight lang="bash">
You probably did a copy that preserved the original group and owner of these files. Within linux internally the owner and group is basically just an id.
tar xf archive.tar.xz
tar xf archive.tar.gz
</syntaxhighlight>


==== How To Extract and Decompress a .bz2/.tbz2 File ====
You can change the ower and group to an existing owner and group with the commands chown and chgrp respectively.
See [http://www.cyberciti.biz/faq/linuxunix-how-to-extract-and-decompress-a-bz2-tbz2-file/ this article] from cyberciti.biz.
<syntaxhighlight lang="bash">
bzip2 -d your-filename-here.bz2
# OR
bzip2 -d -v your-filename-here.bz2
# OR
bzip2 -d -k your-filename-here.bz2
# OR
bunzip2 filename.bz2
</syntaxhighlight>


==== Compare zip, tar.xz, tar.gz, 7z ====
== Uppercase S in permissions of a folder and setGID ==
The compression rate comparison is (from best to worst) 7z > tar.xz > tar.gz > zip.  
* [https://www.linux.com/learn/understanding-linux-file-permissions Understanding Linux File Permissions]
* [https://linuxconfig.org/how-to-use-special-permissions-the-setuid-setgid-and-sticky-bits How to use special permissions: the setuid, setgid and sticky bits]
* [https://unix.stackexchange.com/a/27254 Uppercase S in permissions of a folder]
* [https://www.tecmint.com/create-a-shared-directory-in-linux/ How to Create a Shared Directory for All Users in Linux]
* [https://www.geeksforgeeks.org/setuid-setgid-and-sticky-bits-in-linux-file-permissions/ SetUID, SetGID, and Sticky Bits in Linux File Permissions], [https://www.makeuseof.com/what-are-set-uid-get-uid-and-sticky-bits-in-linux-file-permissions/ What are Set UID, Get UID, and Sticky Bits in Linux File Permissions?]


For example, consider qt-everywhere-opensource-src-5.5.0 from http://download.qt.io/official_releases/qt/5.5/5.5.0/single/
I happen to create this case by '''chmod -R 760 ShareFolder'''. To make 'S' to become 's', I just need to use '''chmod -R 2770 ShareFolder'''.
* zip 540M
* tar.xz 305M
* tar.gz 436M
* 7z 297M


==== Extract one files from tar.gz ====
== immutable files ==
Extract a file called etc/default/sysstat from config.tar.gz tarball:
[https://www.linuxtechi.com/file-directory-attributes-in-linux-using-chattr-lsattr-command/ Manage file and directory attributes using chattr and lsattr command]
<pre>
$ tar -zxvf config.tar.gz etc/default/sysstat
</pre>
Noe that a new directory etc/default will be created under the current directory if it does not exist.


[http://www.cyberciti.biz/faq/linux-unix-extracting-specific-files/ Wildcard based extracting]
== Display files sorted by modified date in a directory recursively ==
 
* [http://stackoverflow.com/questions/5566310/how-to-recursively-find-and-list-the-latest-modified-files-in-a-directory-with-s stackoverflow.com]
You can also extract those files that match a specific globbing pattern (wildcards). For example, to extract from cbz.tar all files that begin with pic, no matter their directory prefix, you could type:
{{Pre}}
<pre>
stat --printf="%y %n\n" $(ls -tr $(find DIRNAME -type f))
$ tar -xf cbz.tar --wildcards --no-anchored 'pic*'
</pre>
</pre>
To extract all php files, enter:
* [http://superuser.com/questions/416308/list-files-recursively-and-sort-by-modification-time superuser.com]
<pre>
{{Pre}}
$ tar -xf cbz.tar --wildcards --no-anchored '*.php'
find -type f -printf '%T+\t%p\n' | sort -n
</pre>
</pre>
Both of methods give the same output. Note the latest changed file is shown at the bottom of the output.


=== Show folder size for one level only ===
== Sort files by their size ==
use the '-S' option.
{{Pre}}
ls -lS
</pre>
 
== Files starting with a dash (meta-characters) ==
[https://www.cyberciti.biz/faq/linuxunix-move-file-starting-with-a-dash/ Move File Starting With A Dash]
{{Pre}}
$ > '-foo.txt'
$ rm "-foo.txt"
rm: invalid option -- 'o'
Try 'rm ./-foo.txt' to remove the file '-foo.txt'.
Try 'rm --help' for more information.
$ rm -- -foo.txt
</pre>
 
== Inodes ==
* https://en.wikipedia.org/wiki/Inode
* [https://www.stackscale.com/blog/inodes-linux/ Inodes in Linux: limit, usage and helpful commands]
* [https://linuxhandbook.com/inode-linux/ Everything You Need to Know About inodes in Linux]
 
== Recover Deleted Files ==
[https://www.makeuseof.com/tag/recover-deleted-files-from-your-linux-system/ How to Recover Deleted Files on Linux]
 
= alias =
https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/
 
{{Pre}}
$ alias # list all aliases
$ alias | grep ls
$ unalias ls
$ alias ls='ls --color=auto' # save it in ~/.bash_profile or ~/.bashrc
$ alias server_name="ssh -v -l john 192.168.1.11" # or modify /etc/hosts
$ alias open='xdg-open'
$ alias sshnocheck='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias scpnocheck='scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias sshserver='ssh [email protected]'
$ alias checkport='sudo lsof -i -P -n | grep LISTEN'
</pre>
'''NOTE''' the last column of the output from "checkport" will show '''who can connection to the port'''. For example, if it shows "127.0.0.1:10999 (LISTEN)", it means only the server can connect to port 10999. If it shows "*:22 (LISTEN)", it means any machines can connect to the server through port 22.
 
To avoid using the alias, use one of the following ways (eg use the command's full path)
{{Pre}}
$ \ls
$ /bin/ls
$ command ls
$ 'ls'
</pre>
 
Useful aliases (Added to ~/.bashrc)
<pre>
<pre>
du --max-depth=1 -h
alias nano="nano -c --softwrap"
</pre>
</pre>
The graphical tool is called '''Disk Usage Analyze''' which is already available on Ubuntu.


=== Soft link ===
We can use the [https://stackoverflow.com/a/20111180 backslash to escape the double quote (or others like dollar sign)].
 
If a command needs the sudo right, include the command inside alias. In the following example, if we skip "sudo" then running the command "sudo lsof2" will result in an error: ''sudo: lsof2: command not found''.
<pre>
<pre>
ln -s /full/path/of/original/file /full/path/of/soft/link/file
alias lsof2="sudo lsof -i -P | egrep \"PID|LISTEN\""
</pre>
</pre>


=== Configure Postfix to use Gmail as a Mail Relay ===
Use '''unalias [alias name]''' to remove an alias.
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/


=== Backup ===
== Find file defining an alias ==
* [http://rdiff-backup.nongnu.org/index.html rdiff-backup]. See https://opensource.com/life/16/3/turn-your-old-raspberry-pi-automatic-backup-server
[https://unix.stackexchange.com/a/176301 how to find file defining an alias]. It works on macOS. Many of them are defined in ''~/.oh-my-zsh/lib/directories.zsh''. Another way (without saving) is [https://stackoverflow.com/a/58224674 How to find out where alias (in the bash sense) is defined when running Terminal in Mac OS X].
* Use dropbox folder.


If we don't want to install dropbox software, we can install bash dropbox uploader: http://www.andreafabrizi.it/?dropbox_uploader OR https://github.com/andreafabrizi/Dropbox-Uploader
= lolcat - bring color to text =
{{Pre}}
sudo apt-get install ruby
sudo gem install lolcat
lolcat -h
lolcat --version
fortune | lolcat


It allows to upload/download/delete/list files and show info of user. The version I am using is v0.9.7. It works on linux, Windows/Cygwin, Raspberry Pi, etc.
ps | lolcat
man ls | lolcat


I install it under
lolcat test.R
'''~/Downloads/andreafabrizi-Dropbox-Uploader-cdc2466 directory'''


Instruction with screenshots: http://www.jobnix.in/dropbox-command-line-interface-cli-client/
sudo apt install figlet
figlet Merry Christmas | lolcat


Sample usages:
alias lolls="ls -l | lolcat"
<pre>
lolls
./dropbox_uploader.sh  list /
./dropbox_uploader.sh  upload ~/Desktop/ConfigurateNote.txt
</pre>
</pre>


=== Running a cron job as a user ===
= File manager =
==== [http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/ Some examples] ====
== Cloud commander ==
* A specific time
* https://cloudcmd.io/
* https://www.ostechnix.com/cloud-commander-a-web-file-manager-with-console-and-editor/. You can upload files from the Cloud services like Google drive, Dropbox, Amazon cloud drive, Facebook, Twitter, Gmail, GtiHub, Picasa, Instagram and many.
 
= diff =
== Run diff with large files ==
diff (or even better the cmp command) works fine with 8G fastq files. Note cmp compare files byte by byte so it probably won't run out of memory. [https://superuser.com/a/690732 How to diff large files on Linux].
 
Another strategy is to split a large file into small pieces. For example,
<pre>
<pre>
MIN HOUR DOM MON DOW CMD
split -b 500MB FILEname # into 500MB files each
30 08 10 06 * /home/ramesh/full-backup
split -l 200 FILEname   # into smaller files with 200 lines each
#   30 – 30th Minute
#   08 – 08 AM
#  10 – 10th Day
#  06 – 6th Month (June)
#  * – Every day of the week
</pre>
* Twice a day
<pre>
00 11,16 * * * /home/ramesh/bin/incremental-backup
#   00 – 0th Minute (Top of the hour)
#    11,16 – 11 AM and 4 PM
#    * – Every day
#    * – Every month
#    * – Every day of the week
</pre>
* Every 10 minutes
<pre>
*/10 * * * * /home/ramesh/check-disk-space
</pre>
</pre>


==== crontab ====
'''Meld''' freezes When I tested it with two large files (800k & 936k lines coming from human gtf files). Actually the whole linux system became unresponsive.
* crontab cron-file-winter; crontab -l
 
Actually Meld is sluggish when it is used in small files in Odroid XU4 running Ubuntu 16.04 MATE. I have used Meld 3.14.2 and the latest 3.16.2.
 
== Kompare ==
https://apps.kde.org/en/kompare
 
Meld cannot change theme. So if my desktop has a dark theme, meld is hard to read.
 
Kompare still has a light them.


Make sure the .sh file gives a complete path. For example,
== Directory ==
<pre>
{{Pre}}
#!/bin/sh
diff -qr dir1 dir2
R --vanilla  < arraytoolsip.R
</pre>
</pre>
does not work in cron job although it works perfect when we manually run it from the right path. The sh file should be
where '''-q''' means to report only when files differ and '''-r''' is to recursively compare any subdirectories found.
 
== diff & colordiff-color on terminal: compare side by side ==
PS. For a GUI version of diff, [http://meldmerge.org/ Meld] works fine.
Need to install first. apt-get install colordiff. http://www.cyberciti.biz/programming/color-terminal-highlighter-for-diff-files/
<pre>
<pre>
#!/bin/sh
sudo apt-get install colordiff
R --vanilla  < $HOME/Dropbox/scripts/arraytoolsip.R
diff -y file1 file2 | colordiff
# Ignore same rows (two ways):
# diff -C0 file1 file2 | colordiff
# diff -U0 file1 file2 | colordiff
 
# On systems that I have no root right, I need to install it from the source
# (just need to run 'make')
$ diff file1 file2 | ~/bin/colordiff-1.0.18/colordiff.pl
</pre>
</pre>
where -y option means to show the output in two columns.


==== PATH and Shell ====
[[File:Colordiff.png|150px]]
Cron knows nothing about your shell; it is started by the system, so it has a minimal environment. If you want anything, you need to have that brought in yourself. For example, to use 'ifconfig' command, I need to give it a complete path in my script file.  
 
<syntaxhighlight lang='bash'>
Interpretation of the '''diff''' output:
$ cat syncIP
 
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
The first line of the '''diff''' output will contain:
</syntaxhighlight>
* line numbers corresponding to the first file,
and the cron job
* a letter ('''a''' for add, '''c''' for change, or '''d''' for delete), and
* line numbers corresponding to the second file.
 
In our output above, '''2,4c2,4''' means: "Lines 2 through 4 in the first file need to be changed in order to match lines 2 through 4 in the second file." It then tells us what those lines are in each file:
 
* Lines preceded by a < are lines from the first file (color in red);
* lines preceded by > are lines from the second file (color in green).
* The three dashes ("---") merely separate the lines of file 1 and file 2.
<pre>
<pre>
06 15 * * * /home/MYUSERNAME/Ubuntu\ One/syncIP > $HOME/Ubuntu\ One/ip.txt 2>&1
2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed.
---
> I need to do the laundry.
> I need to wash the car.
> I need to get the dog detailed.
</pre>
</pre>
See [http://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables here] on how to add environment variable into cron environment.


==== Disable mail alert ====
{{Pre}}
If something went wrong with executing a cron job, cron will output a message "You have new mail in /var/mail/$USER". You can open this file using a text editor. To disable this alert, run ''''crontab -e''' (see [http://www.cyberciti.biz/faq/disable-the-mail-alert-by-crontab-command/ this post]
colordiff -ur path1 path2
<pre>
0 1 5 10 * /path/to/script.sh >/dev/null 2>&1
# OR
0 1 5 10 * /path/to/script.sh > /dev/null
</pre>
</pre>
If you change -ur to -urN then that will also show the contents of files that are only present in one of the paths.
[[File:Colordiff2.png|150px]]


=== Running crontab as root ===
The meaning of colors can be found in '''/etc/colordiffrc''' (''man colordiff'' or [https://www.colordiff.org/colordiff.html colordiff web site])
Use '''sudo crontab -e''' to edit. After saving it, no need to initialize it. Use '''sudo crontab -l''' to list the cron job.
* plain=off
* newtext=darkgreen
* oldtext=darkred
* diffstuff=darkcyan
* cvsstuff=cyan


=== Mount drive ===
== git diff --no-index -- file.a file.b ==
==== /etc/fstab ====
[https://stackoverflow.com/a/15110387 Any visual diff in Linux console?]
* https://help.ubuntu.com/community/Fstab
 
* https://help.ubuntu.com/community/UsingUUID
= gnome-terminal =
* [http://www.cyberciti.biz/faq/linux-add-nodev-nosuid-noexec-options-to-temporary-storage-partitions/ Mount /tmp securely]
 
* http://www.thegeekstuff.com/2013/01/mount-umount-examples/
== Remember the session ==
* http://www.instructables.com/id/Using-a-USB-external-hard-drive-with-your-Raspberr/?ALLSTEPS <span style="color: red">Use UUID instead of /dev/sdXY to specify the partition in /etc/fstab to avoid any changes with /dev/sdXY</span>. The UUID can be obtained using
* [http://manpages.ubuntu.com/manpages/xenial/man1/gnome-terminal.1.html gnome-terminal --help-all] '''--tab-with-profile'''
<syntaxhighlight lang='bash'>
** https://stackoverflow.com/questions/17422810/opening-terminal-with-multiple-tabs-using-shell-script
sudo blkid
** https://stackoverflow.com/questions/1700995/start-gnome-terminal-with-multiple-virtualenv-tabs-and-services-pre-titled
</syntaxhighlight>
* [https://askubuntu.com/questions/777833/can-no-longer-set-terminal-title-in-ubuntu-16-gnome-terminal Can no longer set terminal title in Ubuntu 16 (gnome-terminal)]
and the result should be compared with
* [https://askubuntu.com/questions/277543/opening-multiple-tabs-with-gnome-terminal Opening multiple tabs with gnome-terminal]: use '''--tab''' and profile options
<syntaxhighlight lang='bash'>
* [https://superuser.com/questions/72130/save-multiple-gnome-terminal-layout Save multiple gnome-terminal layout?]: '''--load-config''' and '''--save-config''' options. NOTE gnome 3.18 option "--save-config" is no longer supported. But strangely enough, "--load-config" is still there.
sudo fdisk -l
* [https://stackoverflow.com/questions/6048474/how-to-remember-multiple-tabs-session-in-terminal-alike-ff-session-manager How to remember multiple tabs' session in terminal? (Alike FireFox session manager)]: '''--profile=''' and '''--save-config''' options. '''--working-directory''' and '''--tab''' options.
</syntaxhighlight>
* Run '''mount -a''' to remount /etc/fstab without reboot, except the partitions with noauto option.


The following example shows a problem (as found from the output of '''df''' command) with </etc/fstab> where we use /dev/sdXY instead of UUID for specifying hard disks.
The following is proved working on Ubuntu 18.04
<pre>
<pre>
$ sudo blkid
gnome-terminal --tab --working-directory=$HOME/Downloads \
/dev/sda1: LABEL="WD640" UUID="d3a0a512-bf96-4199-9674-f410f22f0a92" TYPE="ext4"
              --tab --working-directory=$HOME/Documents
/dev/sdb1: UUID="afaa4bde-1172-4c54-8b0a-a324ad855355" TYPE="ext4"
</pre>
/dev/sdb5: UUID="fb2a4ada-d80a-4e23-b4a2-67376b8b7e72" TYPE="swap"
 
== Fun: piano ==
[https://www.ostechnix.com/let-us-play-piano-terminal-using-pc-keyboard/ Let Us Play Piano In Terminal Using Our PC Keyboard]
 
= Terminals in grids =
See [[Terminal_multiplexer|Terminal_multiplexer]].
== Tilix ==


$ sudo fdisk -l
== Terminator ==
Disk /dev/sda: 640.1 GB, 640135028736 bytes
...
  Device Boot      Start        End      Blocks  Id  System
/dev/sda1            2048  1250263039  625130496  83  Linux


Disk /dev/sdb: 640.1 GB, 640135028736 bytes
== GNU screen ==
...
  Device Boot      Start        End      Blocks  Id  System
/dev/sdb1  *        2048  1217761279  608879616  83  Linux
/dev/sdb2      1217763326  1250263039    16249857    5  Extended
/dev/sdb5      1217763328  1250263039    16249856  82  Linux swap / Solaris


$ cat /etc/fstab
== tmux* ==
proc            /proc                          proc    nodev,noexec,nosuid 0 0
UUID=afaa4bde-1172-4c54-8b0a-a324ad855355 /    ext4    errors=remount-ro  0 1
UUID=fb2a4ada-d80a-4e23-b4a2-67376b8b7e72 none swap    sw                  0 0
/dev/sdb1      /mnt/WD640                    ext4    rw,nosuid,nodev    0 2


$ df -h
== [http://byobu.co/ Byobu] ==
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1      572G  413G  130G  77% /
...
/dev/sdb1      572G  413G  130G  77% /mnt/WD640
</pre>
To fix the error here, modify the line starting /dev/sdb1 in /etc/fstab and replace it with the UUID. Then run sudo umount /mnt/WD640 and sudo mount -a. Done!
<pre>
~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1      572G  413G  130G  77% /
...
/dev/sda1      587G  283G  275G  51% /mnt/WD640
</pre>


==== usb drive ====
== [https://github.com/Guake/guake Guake] / Yakuake / Tilda ==
* [https://help.ubuntu.com/community/RenameUSBDrive Rename USB drive]
Drop down terminals for the GNOME / KDE / GTK Environments. Great for quick access to a terminal!


Run
= System date/time, ntpd =
<pre>
* [http://www.ubuntugeek.com/install-and-configure-network-time-protocol-ntp-serverclients-on-ubuntu-16-10-server.html Install and configure Network Time Protocol (NTP) Server,Clients on Ubuntu 16.10 Server]
fdisk -l
* [https://www.cyberciti.biz/faq/how-to-bind-ntpd-to-specific-ip-addresses-on-linuxunix/ How to bind ntpd to specific IP addresses on Linux/Unix]
* [https://www.2daygeek.com/check-verify-ntp-sync-is-working-or-not-in-linux-using-ntpq-ntpstat-timedatectl/ How To Verify NTP Setup (Sync) is Working or Not In Linux?]
{{Pre}}
$ timedatectl
      Local time: Mon 2019-06-10 08:37:09 EDT
  Universal time: Mon 2019-06-10 12:37:09 UTC
        RTC time: Mon 2019-06-10 12:37:09
      Time zone: America/New_York (EDT, -0400)
Network time on: yes
NTP synchronized: yes
RTC in local TZ: no
</pre>
</pre>
OR
<pre>
dmesg | grep -i "SCSI"
</pre>
to confirm the USB device is detected.


Now suppose the usb device is found in '''dev/sdb1'''.  
= Linux file timestamps =
<pre>
[https://www.howtogeek.com/517098/linux-file-timestamps-explained-atime-mtime-and-ctime/ Linux File Timestamps Explained: atime, mtime, and ctime]
mkdir /mnt/usb
 
mount -t vfat -o rw,users /dev/sdb1 /mnt/usb
== Change the date/timestamp of a file - touch ==
</pre>
Modify the file relative to its existing modification time
The above mount command assumes the usb drive has Windows vfat partition and ''users'' give non-root users the ability to unmount the drive.
{{Pre}}
If the USB drive is partitioned linux ext2/3, we can merely run mount command as
filename=MyFileName
<pre>
touch -d "$(date -R -r $filename) - 2 hours" $filename # 2 hours before
mount /dev/sdb1 /mnt/usb
touch -d "$(date -R -r $filename) + 2 hours" $filename # 2 hours later
</pre>
</pre>


At the end, run umount command like
See [http://askubuntu.com/questions/62492/how-can-i-change-the-date-modified-created-of-a-file How can I change the date modified/created of a file?]
<pre>
umount /mnt/usb
</pre>


To make the mounting automatically, edit the file '''/etc/fstab'''.
= Find binary file location, '''type''' =
<pre>
* '''which''' - Display the full path of shell commands. See examples from [http://www.cyberciti.biz/faq/unix-linux-which-command-examples-syntax-to-locate-programs/ cyberciti.biz].
/dev/sdb1      /mnt/usb          vfat    defaults        0      0
{{Pre}}
/dev/sdb1      /mnt/usb          ext3    defaults        0      0
$ which ls
/bin/ls
</pre>
* '''whereis''' - locate the binary, source, and manual page files for a command. See examples from [http://www.cyberciti.biz/faq/unix-linux-whereis-command-examples-to-locate-binary/ cyberciti.biz]. 
{{Pre}}
$ whereis ls
ls: /bin/ls /usr/share/man/man1p/ls.1p.gz /usr/share/man/man1/ls.1.gz
</pre>
</pre>
and run
* '''type''', [https://www.cyberciti.biz/howto/finding-a-path-of-a-linux-command-like-a-pro/ How to find a path of a Linux command like a pro]
<pre>
{{Pre}}
mount -a
$ type ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
</pre>
</pre>


==== Mount an iso file ====
* '''locate'''. Use '''locate''' command mindfully. It is used to find the location of files and directories. Note that locate does not search the files on disk rather it searches for file paths in a database. For example, the following command will search .png files over the system (not only the personal directory).
* http://www.shellhacks.com/en/Mounting-an-ISO-Image-in-Linux
{{Pre}}
<syntaxhighlight lang='bash'>
locate "*.png"
sudo mkdir -p /mnt/mount_point # create a mount point
</pre>
sudo mount -o loop /home/user/disk.iso /mnt/mount_point
: See [https://superuser.com/a/705854 How to use updatedb command as an ordinary user?], [https://hpc.nih.gov/training/handouts/Data_Management_for_Groups.pdf#page=53 Use updatedb and locate to index files].
mount  # verify
</syntaxhighlight>
 
==== Mount remote Windows share ====
* http://www.shellhacks.com/en/HowTo-Mount-Remote-Windows-Partition-Share-under-Linux


==== exFat ====
= find: Find a file =
http://www.howtogeek.com/235655/how-to-mount-and-use-an-exfat-drive-on-linux/
find operates ''recursively'' into sub folders.


==== NTFS usb drive in xubuntu ====
== -iname ==
http://xflinux.blogspot.com/2011/01/mount-ntfs-volumes-automatically-in.html
Search by a file name
<pre>
{{Pre}}
sudo apt-get install ntfs-config
$ find . -type f -name "abc*" # find a file starting with abc
$ find . -iname '*.txt'  # -iname or -name is necessary
</pre>
</pre>
Now go to Applications>> System>> Ntfs Configuration Tool


Expand the "Advanced Configuration" and select all those partitions you want to be auto mounted and writable( The tool will detect all partitions at its startup).
It also works for searching files on subdirectories.
 
{{Pre}}
Make sure the " Enable write support for internal devices" option is selected. Now click Close.
$ find . -name transcripts.gtf
./RH_bio/transcripts.gtf
./dT_ori/transcripts.gtf
./dT_tech/transcripts.gtf
./dT_bio/transcripts.gtf
./RH_ori/transcripts.gtf
./RH_tech/transcripts.gtf
</pre>


==== Many drives, one folder ====
== -mtime, -ctime, -atime argument ==
* [http://www.linuxjournal.com/content/many-drives-one-folder mhddfs] program.
Find files modified in 10 days.
{{Pre}}
$ find . -ctime -10 # include subdirectories
.
./mediawiki-1.32.0.tar.gz
./d
./d/deepSurv.pdf
</pre>


=== run commands in a background and allow log off ===
Find files modified in one day and contain string 'est'
<syntaxhighlight lang='bash'>
{{Pre}}
nohup /path/to/script >output 2>&1 &
$ find . -mtime -1 -exec grep --with-filename est {} \;
</syntaxhighlight>
</pre>


Or to [http://stackoverflow.com/questions/10408816/how-do-i-use-the-nohup-command-without-getting-nohup-out disable output and be more safe]. It also explains the concept of '''file descriptor/fd''' in Unix.
<span style="color: red">If the search directory is not the current directory, we need to add a forward slash to the directory name.</span>
<syntaxhighlight lang='bash'>
{{Pre}}
nohup command </dev/null >/dev/null 2>&1 &
$ find ~/Desktop -iname '*.txt' # Not working
</syntaxhighlight>
$ find ~/Desktop/ -iname '*.txt' # Working
</pre>


See also [https://en.wikipedia.org/wiki/Process_substitution#Anonymous_named_pipe Anonymous named pipe].
The [http://content.hccfl.edu/pollock/unix/findcmd.htm following example] shows we can list multiple search criteria. The “‑r” option in tar appends files to an archive. '''xargs''' is a handy utility that converts a stream of input (in this case the output of find) into command line arguments for the supplied command (in this case tar, used to create a backup archive).
{{Pre}}
find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar
</pre>


=== Notepadqq - Notepad++-like editor ===
[https://www.quora.com/What-is-the-difference-between-mtime-atime-and-ctime What is the difference between mtime, atime and ctime?]
[http://www.ubuntugeek.com/notepadqq-the-linux-source-editor.html Notepadqq]. It is written using Qt. It does not have printing function:(
* mtime (modification time) indicates the time the contents of the file has been changed. Mind you, only the contents. Not the attributes.  
* ctime (change time) is the timestamp of a file that indicates the time that it was changed. Now, the modification can be in terms of its content or in terms of its attributes.
* atime (access time) is the timestamp that indicates the time that a file has been accessed.


=== nano editor ===
== xargs ==
==== Permission denied and '''sudoedit''' command ====
See [[Linux_Programming#xargs|Linux Programming]]
When I run 'nano tmp', I got a message: Error reading /home/odroid/.nano/search_history: Permission denied. Press Enter to continue.
<syntaxhighlight lang='bash'>
odroid@odroid:~$ ls -ld /home/odroid/.nano
drwxr-xr-x 2 root root 4096 Feb 12 08:01 /home/odroid/.nano
odroid@odroid:~$ ls -l /home/odroid/.nano
total 4
-rw------- 1 root root 15 Feb 12 08:01 search_history
</syntaxhighlight>
A simple solution is
<syntaxhighlight lang='bash'>
sudo chown -R odroid:odroid /home/odroid/.nano  # note '-R' has to be capital
</syntaxhighlight>


This seems to be a bug in nano after we use 'sudo nano [file]' (eg 'sudo nano /etc/chromium-browser/default') when the 'nano' program has not been run before. 
== -exec COMMAND {} \; ==
* [http://superuser.com/questions/159823/how-can-i-solve-this-error-i-get-when-i-commit-changes-on-an-svn-repository-from superuser.com]. A better habit to get into is to use <span style="color: red">sudoedit</span> or <span style="color: red">sudo -e</span> instead of 'sudo nano'.
<ul>
* Why use [http://bencane.com/2012/02/26/sudoedit-securely-allow-users-to-edit-files/ 'sudoedit' or 'sudo -e'] - security reason
<li>Search and list files with details
* http://superuser.com/questions/785187/sudoedit-why-use-it-over-sudo-vi
<syntaxhighlight lang='sh'>
* '''visudo''' is used to edit /etc/sudoers file only
find . -type f -name "*street*" -exec ls -lh {} \;
 
The bottom line is use something like below for editing system files
<syntaxhighlight lang='bash'>
EDITOR=nano sudoedit /etc/chromium-browser/default
</syntaxhighlight>
</syntaxhighlight>
'''-exec ls -lh {} \;''' executes the '''ls -lh''' command on each found file. The '''{}''' is a placeholder for the current file, and '''\;''' indicates the end of the -exec command.


==== show line number/cursor position ====
<li>[https://unix.stackexchange.com/a/12904 How to run find -exec?], [https://stackoverflow.com/a/6085237 Using semicolon (;) vs plus (+) with exec in find]
Use the '''-c''' option for cursor position.
{{Pre}}
<syntaxhighlight lang='bash'>
# This command will run grep chrome on each file individually.
nano -c FILENAME
find . -exec grep chrome {} \;
</syntaxhighlight>


==== syntax highlight ====
# This command will run grep chrome on batches of files, reducing the number of times the command is executed.
[http://askubuntu.com/questions/90013/how-do-i-enable-syntax-highlighting-in-nano Add a syntax highlight support for some languages]
# Using + can significantly improve performance
find . -exec grep chrome {} +
</pre>
Note:
* The backslash before ; is to '''escape''' ; so linux won't interpret it directly.
* Command Compatibility: Not all commands support being executed with multiple arguments at once. For example, grep can handle multiple files, but some other commands might not. In other words, while '''-exec COMMAND {} +''' can be more efficient, it’s important to ensure the command you’re using supports this usage and behaves as expected.


<syntaxhighlight lang='bash'>
<li>Find files and execute something (google: find --exec)
$ ls /usr/share/nano/
{{Pre}}
asm.nanorc    html.nanorc  mutt.nanorc    perl.nanorc    ruby.nanorc
$ find ./ -name "*.tar.gz" -exec tar zxvf {} \;
c.nanorc      java.nanorc  nanorc.nanorc  pov.nanorc    sh.nanorc
</pre>
groff.nanorc  man.nanorc  patch.nanorc  python.nanorc  tex.nanorc
$ cat ~/.nanorc
include /usr/share/nano/sh.nanorc
include /usr/share/nano/c.nanorc
include ~/r.nanorc
</syntaxhighlight>


R syntax highlight file [https://r-forge.r-project.org/scm/viewvc.php/pkg/pkgutils/inst/highlighting/R.nanorc?view=markup&root=opm r.nanorc]. Note that I have to comment out line 29 starting with 'header'. A personal copy is saved in [https://gist.github.com/arraytools/8b52cc749c2fa6d45c16 github].
<li>Find and move files to a new directory
{{Pre}}
find OLDDIR -type f -exec mv -t NEWDIR {} +
</pre>


=== vi keys ===
<li>[http://unix.stackexchange.com/questions/41550/find-the-total-size-of-certain-files-within-a-directory-branch Find the total file size of a list of files].
* ctrl +f: page down. Ctrl +b: page up.  
* ^: beginning of a line. $: end of a line.
* command mode : this is the default when you run vi. Hit Esc key to return to the command mode. Command mode is right for moving about a file, copying or deleting a line, saving a file, etc.
* edit mode : hit "i" (insert text before cursor position) or "a" (add text after cursor position) to enter the edit mode.
* leave edit mode: "ESC"
* delete entire line: "dd"
* undo: "u"
* search forward: "/pattern" (case sensitive). Hit "n" to repeat search.
* search backward: "?pattern" (case sensitive). Hit "n" to repeat search.
* save: ":w"
* quit: ":q"
* quit without saving: ":q!"
* save and quit: ":wq"


Some helps
<li>[https://unix.stackexchange.com/a/196917 What is meaning of {} + in find's -exec command?]
* http://mathlab.cit.cornell.edu/local_help/vi.html
* http://www.lagmonster.org/docs/vi.html and [http://www.lagmonster.org/docs/vi2.html more complete one].
* [http://askubuntu.com/questions/418396/what-is-the-difference-between-vi-and-vim Difference between vi and vim]. Especially Vim allows the screen to be split for editing multiple files. Use ":split" to split a screen using the same file, ":split filename" to split the screen using a new file and "Ctrl-w + Ctrl-w" to switch screens/'''viewports'''. More keyboard controls can be found at [https://www.linux.com/learn/tutorials/442415-vim-tips-using-viewports linux.com].


=== Cloud ===
<li>[http://unix.stackexchange.com/questions/179346/why-does-find-exec-cmd-need-to-end-in?rq=1 Why does 'find -exec cmd {} +' need to end in '{} +'?]


http://slidedecks.wilmoore.com/2012-confoo/diy-private-cloud-using-virtualBox-and-chef/#66
<li>[http://unix.stackexchange.com/questions/12902/how-to-run-find-exec How to run find -exec?]
The following will find out the total file size of the 'accepted_hits.bam' file under all sub-directories.
{{Pre}}
find ./ -iname "accepted_hits*" -exec du -ch {} + | grep total$
</pre>
where '-c' produces a grand total, and will substitute {} with the filename(s) found in '''-exec'''.
</ul>


http://www.datacentermap.com/blog/cloud-software-389.html
== How to find and delete directory recursively ==
[https://www.cyberciti.biz/faq/how-to-find-and-delete-directory-recursively-on-linux-or-unix-like-system/ How to find and delete directory recursively on Linux or Unix-like system]. Application: recursively remove backups older than 30 days.


* [http://www.openstack.org/ OpenStack]:Open source software for building private and public clouds. Great for large infrastructures. Cf: Amazon Elastic Compute Cloud (EC2).
== Find all soft link files ==
** http://www.tikalk.com/alm/blog/expreimenting-openstack-essex-ubuntu-1204-lts-under-virtualbox
<pre>
** http://www.ibm.com/developerworks/cloud/library/cl-openstack-cloud/
find /tmp -type l
* [http://incubator.apache.org/cloudstack/ CloudStack]
</pre>
* [http://www.eucalyptus.com/ Eucalyptus] API compatible with Amazon EC2
* [http://owncloud.org/ ownCloud]. Cf: Dropbox. [https://www.howtoforge.com/tutorial/owncloud-install-debian-8-jessie/ Install owncloud on Debian 8], [https://www.howtoforge.com/tutorial/install-owncloud-client-on-ubuntu-14-04/ install owncloud client on Ubuntu 14.04].


Commercial cloud services
== Recursive statistics on file types in directory? ==
* [https://www.digitalocean.com/ DigitalOcean] - simple pricing. One droplet = one server.
[https://unix.stackexchange.com/a/18508 You could use '''find''' and '''uniq''' for this]. This is fast!
* Amazon EC2
* Google cloud
* Microsoft Azure


=== U-boot ===
<pre>
http://www.denx.de/wiki/U-Boot
$ find . -type f | sed 's/.*\.//' | sort | uniq -c
</pre>


=== Pandora linux client ===
== Exclude or Ignore Files ==
* [http://kevinmehall.net/p/pithos/ Pithos] (GUI)
[https://www.cyberciti.biz/faq/find-command-exclude-ignore-files/ Find command Exclude or Ignore Files (e.g. Ignore All Hidden .dot Files )]
* [http://6xq.net/projects/pianobar/ Pianobar] (Command line)


=== COW (copy on write) file system ===
== Avoid Permission Denied Messages ==
The cow filesystem was found on xubuntu live CD. See http://en.wikipedia.org/wiki/Copy-on-write
[https://www.cyberciti.biz/faq/bash-find-exclude-all-permission-denied-messages/ How to fix find command permission denied messages]
* Redirecting ALL standard error (not only permission denied error): '''2>/dev/null'''.
{{Pre}}
find . -iname "data*.txt" -print 2>/dev/null
</pre>
* Focus on the 'permission denied' message: '''grep -v "Permission denied" '''
{{Pre}}
find / -name foo 2>&1 | grep -v "Permission denied"
</pre>


=== Apache redirection ===
== Find Files That Have Been Modified Recently in Linux ==
http://cran.r-project.org/mirror-howto.html
[https://www.baeldung.com/linux/recently-changed-files Find Files That Have Been Modified Recently in Linux]


=== Important linux directories ===
== fd: The Find Command Alternative ==
* /bin - executables used by the base system
[https://ostechnix.com/fd-find-command-alternative/ Fd: The Find Command Alternative For Mastering File Search In Linux]
* /boot
* /dev
* /etc - configuration files
* /media
* /mnt
* /opt - optional application packages
* /proc - process information only
* /sbin - critical executables for running the system, but should be used by superuser
* /usr - non-critical files. Inside is /usr/bin, which contains most of the libraries used by apps.
* /var - variable data such as databases, mails spools and system logs.


=== Difference of /bin, /sbin, /usr/local/bin, ... ===
= '''grep''': Find a file by searching contents =
* /bin : For essential binaries; e.g. bash, cat, ls.
{{Pre}}
* /sbin : is similar to /bin but for scripts with superuser (root) privileges required; e.g. shutdown command is located here. Local users have to use sudo to run binaries here.
grep -r -i "Entering" ~/Downloads/R-3.0.0/
* /usr/bin : Same as first, but for general system-wide & non-essential binaries; e.g. grep, zip, docker, etc.
</pre>
* /usr/sbin : Same as above, but for scripts with superuser (root) privileges required.
where '''-r''' means recursively searching the directory and '''-i''' means case insensitive.
* /usr/local/bin or /usr/local/sbin for system-wide available (personal) scripts.  


If you want to create your own scripts and make them available to all users, you’re pretty safe adding them to /usr/local/bin. Or to add my scripts to my local bin (~/bin) and then I create a symbolic link in /usr/local/bin to the commands I want to make public. As a result, I can manage all my scripts from the same directory but still make some of them publicly available since /usr/local/bin is added to $PATH. See [http://blog.taylormcgann.com/2014/04/11/difference-bin-sbin/ this post].
Sometimes using '''-R''' is more effective because of the symbolic links issue.
{{Pre}}
$ grep -r -i phpmyadmin /etc/apache2/ # nothing returned
$ grep -R -i phpmyadmin /etc/apache2/
</pre>


=== DHCP lease time ===
We can also display the row numbers for matches by using the '''-n''' parameter in grep.
{{Pre}}
# What variants appear in dbsnp
grep -n 'rs[0-9]' XXX.vcf
</pre>


On Windows, it is 8 days.
To exclude lines with a pattern, using the '''-v''' parameter.
{{Pre}}
# How many variant were called
grep -v "^#" XXX.vcf | head
</pre>
 
To exclude binary files, use '''-I''' parameter.


=== Check a file's encoding ===
To show only matched filenames, using the '''-l''' parameter.
<pre>
{{Pre}}
file -bi myfile
grep -l "iterator" *.cpp
# if we add '-n', the '-n' option won't work.
</pre>
</pre>
For example,
 
<pre>
To search with certain file extensions, use '''--include''' argument; see [https://stackoverflow.com/questions/12516937/grep-but-only-certain-file-extensions this post].
mli@PhenomIIx6:~$ file -bi Downloads/hmv_.rc
{{Pre}}
text/x-c++; charset=utf-16le
grep -r -i --include \*.h --include \*.cpp KEYWORD ~/path[12345] 
mli@PhenomIIx6:~$
# escape with \ just in case you have a directory with asterisks in the filenames
</pre>
</pre>


=== Know you system using the command line ===
[https://www.linuxuprising.com/2021/11/how-to-find-all-files-containing.html How To Find All Files Containing Specific Text On Linux From The Command Line]
* https://www.howtoforge.com/tutorial/get-to-know-your-system/
{{Pre}}
grep -Rni --exclude-dir={Private,Personal} --include={*.txt,*.js} 'text' ~/Documents
# Exclude hidden directories
grep -R --exclude-dir=".*" 'text' ~/Documents
</pre>


=== System monitor tools ===
The only issue with using the -f argument is that grep is going to attempt to interpret the keywords as if they are patterns, which can slow it down when parsing against an extremely large file. So you can also specify the -F parameter, which tells grep to only do exact matches against the strings.
* [http://www.ubuntugeek.com/install-linux-dash-web-based-monitoring-tool-on-ubntu-15-04-server.html Linux Dash] Web based monitoring tool. Source code is on [https://github.com/afaqurk/linux-dash github].
<pre>
* [http://www.nagios.org Nagios]
grep -f searchstringsFile filetosearch > output.txt
* [http://www.ubuntugeek.com/how-to-install-icinga-nagios-fork-in-ubuntu-12-10-server.html icinga (Nagios fork)]


=== Git and Github ===
# -F, --fixed-strings
Check out the [[Github|Github]] page.
grep -F searchstring filetosearch > output.txt
</pre>


=== Bitbucket (free for 5 users) ===
If the pattern is saved in a file, use the '''-f''' parameter
[https://confluence.atlassian.com/display/BITBUCKET/Bitbucket+101  Bitbucket 101]
{{Pre}}
grep -f PATTERNFILE INPUTFILE
</pre>


* Unlimited private repos
If there are two keywords, use the following
* Code reviews
{{Pre}}
* JIRA integration
$ grep "begin\|completed" --color swarm_58606147_0.o  # needs an escape
* REST API
begin 2018-01-12 14:46:05
* Custom domains
alignment is completed 2018-01-12 16:45:24
marking duplication is completed 2018-01-12 17:52:01
assign read group is completed 2018-01-12 18:22:49
indel re-alignment is completed 2018-01-12 19:29:32
BQSR is completed 2018-01-12 22:26:22
GATK is completed 2018-01-12 23:43:3
$ egrep "begin|completed" --color swarm_58606147_0.o
# no need an escape if we use extended regular expressions
</pre>
We can use R to compute the time spent in each step; see [[R#Dealing_with_date|Dealing with dates]].


See this [https://answers.atlassian.com/questions/148713/sourcetree-commit-author-change-update post] to know how to fix the problem of unknown author. In short, when I uncheck "Use global user setting" from Repository-> Repository Settings -> Advanced does the commit author change as expected.
Check https://www.howtoforge.com/tutorial/linux-grep-command/ for more examples
* Using grep to search only for words / exact match ("-w" option)
* Using grep to search two different words  (egrep -w 'word1|word2' /path/to/file)
* Count line for matched words  ("-c" option)
* Grep invert match ("-v" option)
* How to list only the names of matching files ("-l" option)


See [http://blog.bitbucket.org/2011/12/21/mobile-apps-for-bitbucket/ here] for a list of Android apps related to bitbucket.
== Preserve colouring after piping grep to grep ==
https://stackoverflow.com/a/2327216


=== Image ===
Use grep '''--color=always''' .For example, grep --color=always KEYWORD Myfile | more.
==== Convert an image file to a different format (eg icon) ====
Using the [http://www.imagemagick.org/script/index.php imagemagic] program.
<syntaxhighlight lang='bash'>
convert winamp-ncrow.png -resize 32x32 winamp-ncrow.ico
</syntaxhighlight>


==== Remove GPS metadata from jpg files ====
== Include/follow soft/symbolic link files ==
<syntaxhighlight lang='bash'>
grep '''grep -Rl''' instead of "grep -rl". Recall "-l" is to list filename only. See "man grep".
sudo apt-get install libimage-exiftool-perl
exiftool -gps:all= -xmp:geotag= image.jpg
</syntaxhighlight>


==== Edit Svg image ====
== Compressed files ==
Inkscape
'''zgrep''' or '''zipgrep''' command


==== Animated gif ====
== GUI ==
https://www.howtoforge.com/tutorial/how-to-generate-a-animated-gif-or-movie-out-of-images-on-linux/#using-photofilmstrip
A GUI version of a tool to search files is [http://searchmonkey.embeddediq.com/ '''searchmonkey'''] (open source, Linux, Windows). On Ubuntu, we install it by
 
=== login shell vs interactive shell ===
* http://stackoverflow.com/questions/18186929/differences-between-login-shell-and-interactive-shell
8 http://serverfault.com/questions/8882/what-is-the-difference-between-a-login-and-an-interactive-bash-shell
 
# '''login shell''' - non desktop environment. ~/.bash_profile is sourced for the bash shell.
# '''interactive shell''' - Ctrl+Alt+t to open a terminal from a graphical mode (desktop environment).  ~/.bashrc is source. We usually edit ~/.bashrc to set up the environment to include fancy prompt, set aliases, set history options, or define custom shell functions.
export environment variables
# Both a '''login shell and an interactive one'''. SSH (Putty) to connect to a remote machine.
# When a shell runs a script or a command passed on its command line, it's a '''non-interactive, non-login shell'''.
 
=== History of commands ===
* [http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/ 15 Examples To Master Linux Command Line History]
 
==== history command with date and time ====
* http://www.cyberciti.biz/faq/unix-linux-bash-history-display-date-time/
 
Running the following code once and history will give date and time the next time you issue the '''history''' command.
<pre>
<pre>
echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc
sudo apt-get install searchmonkey
</pre>
</pre>
Note that the original post asks to write the line to ~/.bash_profile but [http://askubuntu.com/questions/121073/why-bash-profile-is-not-getting-sourced-when-opening-a-terminal this is not working in the desktop environment].
It is also useful to change the settings so we can click a filename and open it in the desired text editor. To do that, go to Settings -> Preferences -> System Call -> Text Editor. I enter 'geany' since I want to use geany to open my C programs. '''Note'''. the v2.0 source code needs to be built using i386 gcc library and Qt 4.8.x. Still, I cannot get rid of some errors coming from the source code.  


==== Bang bang - Run a command/Fetch parameters from previous history ====
== -- option ==
* http://unixhelp.ed.ac.uk/shell/tcsh_hist3.html
[https://www.linuxuprising.com/2021/02/how-to-use-grep-search-help-output-to.html How To Use grep To Search The --help Output To Find Out What CLI Arguments That Begin With A Dash Do]
* http://codytaylor.org/2009/09/linux-bang-commands.html
<pre>
* http://craig-russell.co.uk/2011/09/28/bang-bang-command-recall-in-linux.html#.VHXnq3Wx3UY
rm --help | grep -w -- -r
* http://requiremind.com/linux-command-line-tips-become-a-master/
 
# ^P: Move up through the command history list one command at a time.
# ^N: Move down through the command history list one command at a time.
# !!: Run the previous command.             
# !n: Run command number n                       
# !string: Run most recent command starting with characters in string
# !?string: Run most recent command containing characters that match string
# !!*: Fetch parameters from last command


For example,
rm --help | grep -w -- '-[rf]'  # multiple one letter
<pre>
!-1
!4
</pre>
</pre>


=== Listen to HiChannel internet radio ===
== Summary of '''find''' and '''grep''' commands ==
Use [http://radiotray.sourceforge.net/ Radio Tray]
{| class="wikitable"
! Command
! Examples
|-
| find
| find [DIRECTORY]  -iname '*.txt'
find [DIRECTORY] -maxdepth 2 -iname *.php


* http://endroid.blogspot.com/2012/02/listen-hichannel-radio-online-by.html
find -name '*.php' -o -name '*.txt'  # OR operator
* http://abcde9990101.blogspot.com/2011/05/ubunturadio-tray.html
|-
| grep
| grep -r -i "check_samtools" DIRECTORY/
dpkg -l libgtk* | grep  '^i'
|}


I use it to listen m3u file (VLC also supports it too).
= Format the output: column =
This command will make the output of some command easy to read; see [https://youtu.be/AVXYq8aL47Q?t=1732 18 Commands That Will Change The Way You Use Linux Forever].


=== [http://en.wikipedia.org/wiki/Web_analytics Web Analytics Reporting Tools] ===
For example: ''mount | column -t''
* [http://piwik.org/ Piwik] (open source). [https://www.howtoforge.com/tutorial/how-to-install-piwik-with-nginx-on-ubuntu-15-10/ How to Install Piwik with Nginx on Ubuntu 15.10]
* [http://awstats.sourceforge.net/ AWStats]
* [http://www.google.com/analytics/ Google Analytics]


=== Paint.NET like program ===
* [https://www.geeksforgeeks.org/column-command-in-linux-with-examples/ column command in Linux with examples]
* [http://pinta-project.com/ Pinta]
* [https://www.tecmint.com/linux-column-command/ Different Ways to Use Column Command in Linux]
* [http://www.ubuntugeek.com/install-mypaint-on-ubuntu-15-10.html MyPaint]
* [https://www.baeldung.com/linux/display-columns-from-file Display Specific Columns From a File in Linux]


=== [http://calibre-ebook.com/download_linux Calibre] - Read ebook in epub format ===
= Count number of columns: awk =
<pre>
The following command shows the number of columns for the first few rows of a text file.
$ sudo -v && wget -nv -O- https://github.com/kovidgoyal/calibre/raw/master/setup/linux-installer.py | \
{{Pre}}
  sudo python -c "import sys; main=lambda:sys.stderr.write('Download failed\n'); exec(sys.stdin.read()); main()"
head MYFILE | awk '{ print NF}'


2014-03-19 15:54:28 URL:https://raw.github.com/kovidgoyal/calibre/master/setup/linux-installer.py [25423/25423] -> "-" [1]
head MYFILE | awk -F '\t'  '{ print NF}'
Installing to /opt/calibre
Downloading tarball signature securely...
Will download and install calibre-1.28.0-x86_64.tar.bz2
                                Downloading calibre-1.28.0-x86_64.tar.bz2                               
100% [===============================================================================================]
                                                                                                        Downloaded 63255897 bytes
Checking downloaded file integrity...
Extracting files to /opt/calibre ...
Extracting application files...
Creating symlinks...
Symlinking /opt/calibre/fetch-ebook-metadata to /usr/bin/fetch-ebook-metadata
Symlinking /opt/calibre/lrf2lrs to /usr/bin/lrf2lrs
Symlinking /opt/calibre/ebook-convert to /usr/bin/ebook-convert
Symlinking /opt/calibre/ebook-meta to /usr/bin/ebook-meta
Symlinking /opt/calibre/ebook-edit to /usr/bin/ebook-edit
Symlinking /opt/calibre/lrfviewer to /usr/bin/lrfviewer
Symlinking /opt/calibre/calibre to /usr/bin/calibre
Symlinking /opt/calibre/markdown-calibre to /usr/bin/markdown-calibre
Symlinking /opt/calibre/calibre-debug to /usr/bin/calibre-debug
Symlinking /opt/calibre/calibre-parallel to /usr/bin/calibre-parallel
Symlinking /opt/calibre/web2disk to /usr/bin/web2disk
Symlinking /opt/calibre/calibre-server to /usr/bin/calibre-server
Symlinking /opt/calibre/calibre-customize to /usr/bin/calibre-customize
Symlinking /opt/calibre/ebook-polish to /usr/bin/ebook-polish
Symlinking /opt/calibre/ebook-viewer to /usr/bin/ebook-viewer
Symlinking /opt/calibre/calibre-smtp to /usr/bin/calibre-smtp
Symlinking /opt/calibre/lrs2lrf to /usr/bin/lrs2lrf
Symlinking /opt/calibre/ebook-device to /usr/bin/ebook-device
Symlinking /opt/calibre/calibredb to /usr/bin/calibredb
Setting up command-line completion...
Installing bash completion to /etc/bash_completion.d/calibre
Setting up desktop integration...
Creating un-installer: /usr/bin/calibre-uninstall
Run "calibre" to start calibre
</pre>
</pre>


==== Fetch News ====
= Count number of rows in a file: wc =
Several built-in sources like TIME, US NEWS report do not work. It'll show 'http error 404 not found'. The self added RSS feed method (see below) does work!
<pre>
wc -l MYFILE
</pre>


* http://www.howtogeek.com/115178/how-to-convert-news-feeds-to-ebooks-with-calibre/ Teach how to add custom news source
The source code of wc (or any Linux command) can be found by using [http://ubuntuforums.org/showthread.php?t=241328 this method]
* http://manual.calibre-ebook.com/news.html
<pre>
* https://michaeltalbotuk.wordpress.com/2013/03/23/how-to-use-calibre-to-read-newspapers-magazines-for-free/
brb@brb-T3500:~/Downloads$ which wc
 
/usr/bin/wc
=== GNU screen ===
brb@brb-T3500:~/Downloads$ dpkg -S /usr/bin/wc
* https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/
coreutils: /usr/bin/wc
* http://unix.stackexchange.com/questions/7453/how-to-split-the-terminal-into-more-than-one-view
brb@brb-T3500:~/Downloads$ sudo apt-get source coreutils
 
</pre>
How to do it...
* Run '''screen''' command first (run '''sudo apt-get install screen''' if necessary). You are now inside of a window within screen. This functions just like a normal shell except for a few special characters.
* Create screen windows: Ctrl + a, then c. To close a screen window: exit. Once you close all screen windows, you shall see a message ''[screen is terminating]'' on the terminal.
* View a list of open windows: Ctrl + a, then ".
* Switch between windows: Ctrl + a and n for the next window and Ctrl +a and p for the previous window.
* Attaching to and detaching screens: To detach (save) from the current screen session, Ctrl +a, and d (these keyboard shortcuts won't affect current execution). This will drop you into your shell. This is useful when you need to run a time-consuming job or your connection is dropped. To attach to an existing screen, use:
<syntaxhighlight lang='bash'>
screen -r -d
</syntaxhighlight>
* Split screen:
** To split the screen horizontally, Ctrl +a and S (capital).
** To unsplit the screen, Ctrl +a and Q (capital).
** To switch from one to the other: Ctrl +a and TAB.
** Note: After splitting, you need to go into the new region and start a new session via Ctrl + a then c before you can use that area.


=== Display/screen ===
As we can see from the ''coreutils-8.21/src'' directory, there are over 100 C programs including <cat.c>, <chmod.c>, <cp.c>, ...<wc.c>.
==== Turn off/on your monitor via command line ====
* https://systembash.com/how-to-turn-off-your-monitor-via-command-line-in-ubuntu/
* http://askubuntu.com/questions/62858/turn-off-monitor-using-command-line
<syntaxhighlight lang='bash'>
xset dpms force off # Press any key to turn it on
xset dpms force on
xset -q # check the status of the X server settings
</syntaxhighlight>


If we want to turn off/on the screen via ssh, add
= Print certain rows/lines of a text file =
<syntaxhighlight lang='bash'>
The following example will print out lines 10 to 60 of FILENAME.
export DISPLAY=:0.0
<pre>
</syntaxhighlight>
sed -n '10,60p' FILENAME
first before calling the '''xset''' command, or use '-display' argument
</pre>
<syntaxhighlight lang='bash'>
Or to print out line 60,
xset -display :0.0 dpms force off
<pre>
xset -display :0.0 dpms force on
sed -n '60p' FILENAME
</syntaxhighlight>
</pre>
It seems this method is not as fast as I expected. For example, the '''tail''' command will immediately print out the result without waiting!


==== Add new screen/display resolutions ====
= Print a text file with line number: less =
* http://ubuntuforums.org/showthread.php?t=1112186 (tested on UDOObuntu 2 beta 2running Ubuntu 14.04 + SainSmart 9" LCD display. The commands (not persistent) are
[https://www.howtogeek.com/444233/how-to-use-the-less-command-on-linux/ How to Use the less Command on Linux]
<syntaxhighlight lang='bash'>
<pre>
xrandr | grep maximum
less -N myfile
gtf 800 480 59.9  # give some output used in the following line
</pre>
xrandr --newmode "800x480_59.90" 29.53 800 816 896 992 480 481 484 497 -HSync +Vsync
xrandr --addmode "DISP3 BG" 800x480_59.90
xrandr --output "DISP3 BG" --mode 800x480_59.90
</syntaxhighlight>


I cannot find the file /etc/X11/xorg.conf in my UDOObuntu 2 beta 2. It seems this file does not exist anymore. See [http://askubuntu.com/questions/4662/where-is-the-x-org-config-file-how-do-i-configure-x-there this post] about how to re-create it.
= output colored console to html =
Use [https://raw.githubusercontent.com/pixelb/scripts/master/scripts/ansi2html.sh ansi2html.sh]. It only requires gawk.
# Use wget to download it
# sudo apt-get install gawk
# chmod +x ansi2html.sh
# colordiff file1 file2 | ./ansi2html.sh > diff.html


==== export DISPLAY ====
= using a the result of a diff in a if statement =
If we want to run a GUI app on a remote computer (such as Raspberry Pi/Beaglebone Black) and show the GUI app on the remote computer's screen using ssh, we can issue the following command before running the app.
<pre>
<syntaxhighlight lang='bash'>
ls -lR $dir > a
export DISPLAY=:0.0
ls -lR $dir > b
</syntaxhighlight>


=== LVM Demystified ===
DIFF=$(diff a b)
http://www.linuxjournal.com/content/lvm-demystified
if [ "$DIFF" != "" ]
then
    echo "The directory was modified"
fi
</pre>
Another example
<pre>
if [ "$(diff file1.html file2.html)" == "" ]; then echo Same; else echo Different; fi
</pre>


=== Shared library management ===
= Prompt =
http://www.cyberciti.biz/tips/linux-shared-library-management.html
== Colored prompt ==
* http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
* https://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/


# ldconfig : Updates the necessary links for the run time link bindings.
For example, the following code will change the prompt to a light blue color. NOTE that we need <span class="Unicode">&#8726;[ </span> and <span class="Unicode">&#8726;] </span> in order to avoid a problem of miscalculating the cursor's starting position.
# ldd : Tells what libraries a given program needs to run.
{{Pre}}
# ltrace : A library call tracer.
# blue 
# ld.so/ld-linux.so: Dynamic linker/loader.
export PS1='\[\e[1;34m\]\u@\h:\w\$ \[\e[0m\]'    # bright blue (good)
export PS1='\[\e[0;34m\]\u@\h:\w\$ \[\e[0m\]'    # darker blue


=== Install binary software using sudo ===
# yellow
One example ([http://calibre-ebook.com/download_linux Calibre]) is like
export PS1='\[\e[1;33m\]\u@\h:\w\$ \[\e[0m\]'    # bright yellow
<pre>
export PS1='\[\e[0;33m\]\u@\h:\w\$ \[\e[0m\]'    # dark yellow (good)
sudo -v && wget -nv -O- https://raw.githubusercontent.com/kovidgoyal/calibre/master/setup/linux-installer.py | \
 
sudo python -c "import sys; main=lambda:sys.stderr.write('Download failed\n'); exec(sys.stdin.read()); main()"
# red
</pre>
export PS1='\[\e[1;31m\]\u@\h:\w\$ \[\e[0m\]'    # bright red
Note that in wget the option "-O-" means writing to standard output (so the file from the URL is NOT written to the disk) and "-nv" means no verbose.
export PS1='\[\e[0;31m\]\u@\h:\w\$ \[\e[0m\]'     # dark red (good)


If the option "-O-" is not used, we'd better to use "-N" option in wget to overwrite an existing file.
# green
export PS1='\[\e[1;32m\]\u@\h:\w\$ \[\e[0m\]'    # bright green
export PS1='\[\e[0;32m\]\u@\h:\w\$ \[\e[0m\]'    # dark green


See the [http://www.gnu.org/software/wget/manual/html_node/Logging-and-Input-File-Options.html#Logging-and-Input-File-Options Logging] and [http://www.gnu.org/software/wget/manual/html_node/Download-Options.html#Download-Options Download] options in wget's [http://www.gnu.org/software/wget/manual/html_node/index.html manual].
# cyan
export PS1='\[\e[1;36m\]\u@\h:\w\$ \[\e[0m\]'    # bright cyan
export PS1='\[\e[0;36m\]\u@\h:\w\$ \[\e[0m\]'    # dark cyan (good)


<pre>
# purple
      -O file
export PS1='\[\e[1;35m\]\u@\h:\w\$ \[\e[0m\]'    # bright purple (good)
      --output-document=file
export PS1='\[\e[0;35m\]\u@\h:\w\$ \[\e[0m\]'    # dark purple
          The documents will not be written to the appropriate files, but all
          will be concatenated together and written to file.  If - is used as
          file, documents will be printed to standard output, disabling link
          conversion.  (Use ./- to print to a file literally named -.)
</pre>
</pre>


=== Log files ===
[[File:Ps1tweak.png|200px]]
[https://www.digitalocean.com/community/articles/how-to-view-and-configure-linux-logs-on-ubuntu-and-centos DigitalOcean]
 
To make a permanent change, we can add the line to '''~/.bashrc''' file and (is it necessary) un-comment the following line
<pre>
<pre>
ls -lt /var/log
force_color_prompt=yes
</pre>
</pre>


=== '''uptime''' command ===
<syntaxhighlight lang='bash'>
uptime
watch -n 60 uptime
</syntaxhighlight>
=== '''htop''' command ===
* [http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages Understand Linux CPU Load]


=== Linux command similar to ''top'' to show hard disk activity ===
Some of my settings in .bashrc file
Use '''iotop'''. On ubuntu, we can use sudo apt-get install to install it. Use '''sudo iotop''' to launch it.
<pre>
<syntaxhighlight lang='bash'>
# Office Linux Mint, bright blue, display current time
sudo apt-get install iotop
# Example: 12:45PM ~/Downloads$
PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] "


sudo iotop -o -u $USER
# Biowulf and Helix, dark yellow
</syntaxhighlight>
# Example: biowulf:~/R$
PS1='\[\e[0;33m\]\h:\w\$ \[\e[0m\]'
alias nano="nano -c --softwrap"


=== Install [http://hbase.apache.org/ Apache HBase] ===
# Mac, light green
Follow the [http://hbase.apache.org/book/quickstart.html Quick Start] to downloaded hbase tar ball. Suppose we save the tar ball under ~/Downloads folder and extract it in the same directory. We shall edit '''conf/hbase-site.xml''' file according to their instruction. The following is my case.
export PS1="\[\e[0;32m\]mac$\[\e[0m\] "
<pre>
$ tar xzvf hbase-0.98.3-hadoop2-bin.tar.gz
$ cd hbase-0.98.3-hadoop2/
$ cat conf/hbase-site.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hbase.rootdir</name>
    <value>file:///home/brb/Downloads/hbase-0.98.3-hadoop2/hbase</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.dataDir</name>
    <value>/home/brb/Downloads/hbase-0.98.3-hadoop2/zookeeper</value>
  </property>
</configuration>
</pre>
</pre>


Before we follow the getting started guide to launch HBase, we shall make sure JAVA_HOME environment variable is created.  
== Shorten prompt ==
<pre>
[https://askubuntu.com/a/145626 How can I shorten my command line (bash) prompt?] It is useful especially in VM.
$ ls /usr/lib/java
 
$ export JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64
== Add a timestamp to your Bash prompt ==
</pre>
* See '''man 3 strftime''' for the date, time format. In Linux Mint, the date applets uses the '''%A %B %e, %H:%M''' which gives a format like 'Friday July 15, 10:23'.  
Note that the last line may be replaced by
* [http://www.foragoodstrftime.com For a Good Strftime] - Online date/time formatting tool
<pre>
* http://bneijt.nl/blog/post/add-a-timestamp-to-your-bash-prompt/. Set
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:bin/javac::")
: {| class="wikitable"
|-
! PS1 !! Prompt
|-
| default || brb@p45t:~/Downloads$
|-
| PS1='[\D{%F %T}] \u@\h \W\$ ' || [2016-07-08 16:56:48] brb@brb-P45T-A ~/Downloads$
|-
| PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] " || 10:54AM ~/Downloads$
|} From here, we can skip '''%F''' (not showing the date), '''\W''' (not showing the current directory) and change '''%T''' to '''%H:%M''' (not showing seconds).
* Another solution: using '''PROMPT_COMMAND''' variable. http://askubuntu.com/questions/193416/adding-timestamps-to-terminal-prompts. Add this line to the '''~/.bashrc''' file:
{{Pre}}
export PROMPT_COMMAND="echo -n \[\$(date +%H:%M%p)\]\ "
</pre>
and the output will be something like:
{{Pre}}
[07:03AM] user@hostname:~$
</pre>
</pre>
Then we can launch HBase,
<pre style="white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;">
$ ./bin/start-hbase.sh


starting master, logging to /home/brb/Downloads/hbase-0.98.3-hadoop2/bin/../logs/hbase-brb-master-brb-P45T-A.out
== '''zsh''': display time to the right hand side ==
brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$ ./bin/hbase shell
add a line RPROMPT='%*' to ~/.zshrc
2014-07-06 09:51:34,621 INFO  [main] Configuration.deprecation: hadoop.native.lib is deprecated. Instead, use io.native.lib.available
HBase Shell; enter 'help<RETURN>' for list of supported commands.
Type "exit<RETURN>" to leave the HBase Shell
Version 0.98.3-hadoop2, rd5e65a9144e315bb0a964e7730871af32f5018d5, Sat May 31 19:56:09 PDT 2014


hbase(main):001:0> create 'test', 'cf'
= Proxy =
2014-07-06 09:51:49,510 WARN  [main] util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
[https://www.makeuseof.com/tag/best-web-proxies/ The 15 Best Web Proxies for Geo-Blocked Content and Online Privacy]
0 row(s) in 2.0770 seconds


=> Hbase::Table - test
== Listen to pandora in Europe: install squid proxy ==
hbase(main):002:0> list 'test'
http://www.cyberciti.biz/faq/access-pandora-radio-using-proxy-server-outside-usa/
TABLE                                                                         
test                                                                           
1 row(s) in 0.0530 seconds


=> ["test"]
Interestingly, the firefox connection settings should choose '''HTTP Proxy''' instead of 'SOCKS host'.
hbase(main):003:0> exit


brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$ ./bin/hbase
= SSH, scp =
See [[Ssh|ssh]].


shell2014-07-06 09:53:37,480 INFO  [main] Configuration.deprecation: hadoop.native.lib is deprecated. Instead, use io.native.lib.available
= Graphical way to display disk usage =
HBase Shell; enter 'help<RETURN>' for list of supported commands.
* http://www.makeuseof.com/tag/how-to-analyze-your-disk-usage-pattern-in-linux/
Type "exit<RETURN>" to leave the HBase Shell
For example, to use xdiskusage, we run '''apt-get install xdiskusage''' and launch it by '''xdiskusage ~/'''.
Version 0.98.3-hadoop2, rd5e65a9144e315bb0a964e7730871af32f5018d5, Sat May 31 19:56:09 PDT 2014
* Ubuntu has a built-in program called "Disk Usage Analyzer". Just search it from Dash. Looks useful!


hbase(main):001:0> list 'test'
= df : Display disk space =
TABLE                                                                         
{{Pre}}
2014-07-06 09:53:44,373 WARN  [main] util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
df -h
test                                                                           
df -h -T  # show the 't'ype of the file system like tmpfs, ext4, squashfs (snap), vfat
1 row(s) in 1.4800 seconds
df -h -t ext4 # show file systems of given type (ext4 in this example)
df -a    # show all file system (include ones that have a size of zero blocks)


=> ["test"]
df -h | grep -v snap # ignore snap partitions
hbase(main):002:0> put 'test', 'row1', 'cf:a', 'value1'
df -h | grep -v loop
0 row(s) in 0.4460 seconds
</pre>


hbase(main):003:0> put 'test', 'row2', 'cf:b', 'value2'
Note for the NTFS type, it will be reported as '''fuseblk''' by mount or df command.
0 row(s) in 0.0140 seconds


hbase(main):004:0> put 'test', 'row3', 'cf:c', 'value3'
== duf ==
0 row(s) in 0.0050 seconds
[https://www.omgubuntu.co.uk/2022/06/duf-alternative-to-df-command Terminal Tip ‘duf’ is Prettier Alternative to the ‘df’]


hbase(main):005:0> scan 'test'
= Disk encryption =
ROW                  COLUMN+CELL                                             
[https://guardianproject.info/code/luks/ LUKS]
row1                column=cf:a, timestamp=1404654837532, value=value1       
row2                column=cf:b, timestamp=1404654856976, value=value2       
row3                column=cf:c, timestamp=1404654866298, value=value3       
3 row(s) in 0.0560 seconds


hbase(main):006:0> get 'test', 'row1'
== Encrypt files ==
COLUMN                CELL                                                     
[https://www.linuxuprising.com/2021/03/croc-is-tool-for-resumable-encrypted.html croc Is A Tool For Resumable, Encrypted File And Folder Transfers Between Computers (Command Line)]
cf:a                timestamp=1404654837532, value=value1                   
1 row(s) in 0.0280 seconds


hbase(main):007:0> disable 'test'
= rm command and trash can =
0 row(s) in 1.6050 seconds
[https://www.2daygeek.com/rm-command-to-move-files-to-trash-can-rm-alias/ Make “rm” Command To Move The Files To “Trash Can” Instead Of Removing Them Completely]


hbase(main):008:0> drop 'test'
= du/ncdu and block size: Display directory size with sorting and human readable =
0 row(s) in 0.2290 seconds
Use [http://www.cyberciti.biz/faq/unix-disk-usage-command-examples/ ncdu] program (more interactive). Although it is a command line program, we can use the mouse to move through each directory to see its sub-directories.
 
'''ncdu''' can show the hidden directory size. This is useful. For example, '''~/.local/share/Trash''' and '''~/.singularity/docker''' can take a lot of space.


hbase(main):009:0> exit
{{Pre}}
brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$
sudo apt-get install ncdu
ncdu
</pre>
</pre>


=== [http://daniel.haxx.se/docs/curl-vs-wget.html curl vs wget] ===
* http://www.cyberciti.biz/faq/linux-check-disk-space-command/
<pre>
And the ''du'' method.
sudo apt-get install curl
{{Pre}}
du -csh *.jpg          # total is at the bottom
du -sh ~/*              # won't include hidden directories, Fast
du -h ~/ --max-depth=1  # include hidden directories, SLOW
du -h ~/ --max-depth=1 --exclude ".*" | sort -nr | cut -f2 | xargs -d '\n' du -sh
du -a -h ~/  # kilobytes will be used, '-a' is to see all files, not just directories.
du -a ~/ | sort -nr | head -n 10  # sort from the largest file size first (in bytes)
                                  # this includes directories and any files under any directories
du -sh * | sort -hr | head -n 10  # this does not go to subdir; only show files and top directories
</pre>
</pre>
For example, the Download link at the [http://travel.nationalgeographic.com/travel/traveler-magazine/photo-contest/2014/entries/gallery/outdoor-scenes-week-1/ National Geographic Travel Photo Contest 2014] works for '''curl''' but not wget. I can use curl with '''-o''' option but not wget with '''-o''' option in such a case.
The --exclude is to hide hidden directories, '-n' is to compare according to string numerical value, and '-r' is to reverse the result.


=== curl and POST request ===
Note that the 'du' commands may be cheating. See the following screenshot.
* http://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request
* https://learn.adafruit.com/raspberry-pi-physical-dashboard?view=all (the original post I saw)
* http://conqueringthecommandline.com/book/curl


=== wget to download a website ===
[[File:DiskUsage.png|100px]]
* http://linux.about.com/od/commands/a/Example-Uses-Of-The-Command-Wget.htm


To download a copy of a complete web site, up to five levels deep ('-r' option). All files linked to in the documents are are downloaded to enable complete offline viewing ('-p' and '--convert-links' options). Instead of having the progress messages displayed on the standard output, you can save it to a log file with the -o option.
The discrepancy is explained by 'sector'. See http://askubuntu.com/questions/122091/difference-between-filesize-and-size-on-disk. Note: it seems 4096 is what I see from all devices.
<pre>
wget -p --convert-links -r linux.about.com -o logfile
</pre>


=== Apply a patch to source code ===
{{Pre}}
* http://www.cyberciti.biz/faq/appy-patch-file-using-patch-command/.
$ sudo dumpe2fs /dev/sda1 | grep -i "block size"
* http://www.thegeekstuff.com/2014/12/patch-command-examples/
dumpe2fs 1.41.14 (22-Dec-2010)
Block size:               4096


For example [https://groups.google.com/forum/#!topic/tuxedo-tools-users/BVNDDmInU0A Tophat 2.0.12 compatibility with Samtools 1.0],
$ sudo tune2fs -l /dev/sda1 | grep -i "block size"
<pre>
brb@brb-VirtualBox:~/Downloads$ ls
support_for_tophat_1.patch  tophat-2.0.12  tophat-2.0.12.tar.gz


brb@brb-VirtualBox:~/Downloads$ grep -r -i "check_samtools" tophat-2.0.12/
$ sudo fdisk -l | tail
tophat-2.0.12/src/tophat.py:def check_samtools():
$ sudo tune2fs -l /dev/mmcblk0p2 | grep -i "block size"
tophat-2.0.12/src/tophat.py:        check_samtools()
</pre>


brb@brb-VirtualBox:~/Downloads$ cp support_for_tophat_1.patch tophat-2.0.12/src/
To show a file size in terms of blocks, we can use
brb@brb-VirtualBox:~/Downloads$ cd tophat-2.0.12/src/
{{Pre}}
brb@brb-VirtualBox:~/Downloads/tophat-2.0.12/src$ patch tophat.py < support_for_tophat_1.patch
ls -s
patching file tophat.py
Hunk #1 succeeded at 1540 (offset 3 lines).
Hunk #2 succeeded at 1563 (offset 3 lines).
brb@brb-VirtualBox:~/Downloads/tophat-2.0.12/src$ ls
</pre>
</pre>
So for example, if a file takes 150 blocks, and if a block takes 4096 bytes, then the file takes 150*4096/1024 KB on disk.


=== Get external IP address ===
== gdu ==
It seems there is no way to get the external IP address without not using external services.
[https://www.linuxuprising.com/2021/01/gdu-is-fast-console-disk-usage-analyzer.html gdu Is A Fast Console Disk Usage Analyzer (Alternative To ncdu, du, Etc.)]
 
== Find the total size of certain files within a directory ==
[https://unix.stackexchange.com/a/41552 Find the total size of certain files within a directory branch]
<pre>
du -ch ./photos/*.jpg | grep total
find ./photos -type f -name '*.jpg' -exec du -ch {} + | grep total$
</pre>
 
= Apache benchmark (ab) testing =
<pre>
<pre>
curl http://ipecho.net/plain; echo
ab -n 100 -c 10 http://taichimd.us/
# OR
curl ipv4.ipogre.com 
</pre>
</pre>
* http://www.petefreitag.com/item/689.cfm
* http://en.wikipedia.org/wiki/ApacheBench
= Monitor progress of copying/transferring files: pv =
[https://www.howtoforge.com/tutorial/how-to-monitor-progress-of-linux-commands-using-pv-and-progress-utilities/ How to monitor progress of Linux commands using PV and Progress utilities]


=== Domain ===
{{Pre}}
* [https://www.whois.net/ WHOIS LOOKUP]. For example, consider "r-pkg.org" domain,
# Method 1: rsync
** The 'Sponsoring Registrar' shows who is the sponsoring registrar (eg GoDaddy.com).
rsync --progress -a sourceDirectory destinationDirectory
** The 'Registrant Name' shows who registered this domain.
rsync --info=progress2 source dest
* [http://ip-lookup.net/index.php IP-Lookup]. For example, consider "r-pkg.org" domain.
** The linux command line tool 'ping' shows the ip address.
** When we use the ip address to search in the IP-Lookup, the '''IP owner info''' > 'Organization' or 'OrgName' field shows the owner of this IP (eg Digital Ocean, Inc).
** The '''Domain owner info''' there gives the same (or less) information as [https://www.whois.net/ WHOIS LOOKUP].
* [http://www.whoishostingthis.com/ WhoIsHostingThis] or [https://www.webhostinghero.com/who-is-hosting/ webhostinghero] (the returned result will be like Amazon, GoDaddy, CloudFlare, Github, Verizon, etc).


=== Subnet ===
# Method 2: pv
[http://en.wikipedia.org/wiki/IPv4_subnetting_reference IPv4]
sudo apt-get install pv
## copy a single file
pv inputfile > outputfile


* Class A:  255.0.0.0 or /8;
## multiple files or directories
* Class B, 255.255.0.0 or /16;
tar c sourceDirectory | pv | tar x -C destinationDirectory
* Class C, 255.255.255.0 or /24.


For example, in the subnet 192.168.5.0/255.255.255.0 (192.168.5.0/24) the identifier 192.168.5.0 commonly is used to refer to the entire subnet.
## https://stackoverflow.com/a/26226261
docker save <image> | bzip2 | pv | \
    ssh user@host 'bunzip2 | docker load'
</pre>


In the /16 subnet 192.168.0.0/255.255.0.0, which is equivalent to the address range 192.168.0.0–192.168.255.255
= rsync =
See [[Backup|Backup]].


[https://en.wikipedia.org/wiki/IPv6_subnetting_reference IPv6]
== Wireless File Transfer Apps on Linux ==
[https://www.makeuseof.com/wireless-file-transfer-apps-linux/ The 7 Best Wireless File Transfer Apps on Linux]


=== ping command ===
= sudo =
ping uses the '''ICMP''' Echo Message to force a remote host to echo a packet back to the local host. If packets can travel to and from a remote host, it indicates that the two hosts can successfully communicate.
== How to Control sudo Access on Linux ==
https://www.howtogeek.com/447906/how-to-control-sudo-access-on-linux/
<pre>
sudo adduser NEWUSER
sudo usermod -a -G sudo NEWUSER
</pre>


=== Build a home network ===
== sudo vs su ==
* [https://www.youtube.com/watch?v=dhLKwzVIRzI&index=1&list=PL1l78n6W8zyr-wZWJzRppQUjz6gc_EWzt Virtual router] using vSphere. (Good ! It includes an introduction to vSphere installation)
[https://phoenixnap.com/kb/sudo-vs-su-differences The Difference Between sudo and su Explained]: password and shell.
* http://rbgeek.wordpress.com/2012/05/14/ubuntu-as-a-firewallgateway-router/


smart== Troubleshoot and repair network problems ===
== How to Keep ‘sudo’ Password Timeout Session Longer in Linux ==
http://www.linuxuser.co.uk/features/troubleshot-repair-linux-networks
http://www.tecmint.com/set-sudo-password-timeout-session-longer-linux/


=== Monitor network by Cacti (GUI) ===
== How to run multiple commands in sudo ==
* http://www.ubuntugeek.com/install-cacti-monitoring-tool-on-ubuntu-15-10-server.html
https://www.cyberciti.biz/faq/how-to-run-multiple-commands-in-sudo-under-linux-or-unix/
* http://www.cacti.net/


=== Monitor network by command line ===
== Run sudo commands without a password? ==
==== iftop ====
* [https://www.makeuseof.com/using-sudo-without-password/ How to Use sudo Commands Without Password in Linux]
Use the interface top '''[http://www.ex-parrot.com/pdw/iftop/ iftop]''' command. On ubuntu, we need to use '''sudo apt-get install iftop''' and then run it by '''sudo iftop -i eth0'''.
* [https://askubuntu.com/questions/159007/how-do-i-run-specific-sudo-commands-without-a-password How do I run specific sudo commands without a password?]
After that, we can press some keys to toggle options.
* p: port
* s: source
* d: destination


See [http://www.thegeekstuff.com/2008/12/iftop-guide-display-network-interface-bandwidth-usage-on-linux/ thegeekstuff].
= Alternative browsers, text browsers =
See [[Browser|Browser]].


==== [http://humdi.net/vnstat/ vnStat] ====
= Filezilla =
http://www.thegeekstuff.com/2011/11/vnstat-network-traffic-monitor/
[https://wiki.filezilla-project.org/Keyboard_shortcuts Keyboard shortcut]. Especially, Alt+Down=Transfers the currently selected item to an item of the same name in the other pane.


<syntaxhighlight lang='bash'>
= The device is busy =
# 1. Install vnStat
* http://oletange.blogspot.com/2012/04/umount-device-is-busy-why.html
sudo apt-get install vnstat
<pre>
brb@brb-P45T-A:~$ sudo umount /media/brb/TOSHIBA
[sudo] password for brb:
umount: /media/brb/TOSHIBA: device is busy.
        (In some cases useful info about processes that use
        the device is found by lsof(8) or fuser(1))
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
umount: /media/brb/TOSHIBA: device is busy.
        (In some cases useful info about processes that use
        the device is found by lsof(8) or fuser(1))
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
COMMAND  PID USER  FD  TYPE DEVICE  SIZE/OFF NODE NAME
VBoxSVC 5600  brb  18w  REG  8,33 4294967295    3 /media/brb/TOSHIBA/Windows 10.ova (deleted)
brb@brb-P45T-A:~$ kill -9 5600
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
brb@brb-P45T-A:~$
</pre>


# 2. Pick a Interface to Monitor using vnStat
* See http://ocaoimh.ie/2008/02/13/how-to-umount-when-the-device-is-busy/
vnstat -u -i eth0
<pre>
vnstat --iflist
# fuser -m /dev/sdc1
vnstatd -d # start the daemon
/dev/sdc1: 538
ps -ef | grep vnst
# ps auxw|grep 538
donncha 538 0.4 2.7 219212 56792 ? SLl Feb11 11:25 rhythmbox
</pre>
Another handy one is:
<pre>
umount -l /dev/sdwhatever
</pre>
 
= mkfs command =
== dd and mkfs ==
[https://www.howtogeek.com/443342/how-to-use-the-mkfs-command-on-linux/ How to Use the mkfs Command on Linux], [https://www.makeuseof.com/how-to-format-storage-drive-linux-terminal/ How to Format Storage Drives Using the Linux Terminal]
<pre>
dd if=/dev/zero of=~/howtogeek.img bs=1M count=250
mkfs.ext2 ~/howtogeek.img
sudo mkdir /mnt/geek
sudo mount ~/howtogeek.img /mnt/geek
sudo chown dave:users /mnt/geek/


# 3. vnStat Basic Usage
cd /mnt/geek
vnstat
cp ~/Documents/Code/*.? .


# 4. vnStat hours, days, months, weeks Network Data
sudo umount /mnt/geek
vnstat -d
cd /mnt
vnstat -m
sudo rmdir geek
</pre>


# 5. Export the data to Excel or other DB
== Format a USB drive: exfat ==
vnstat --dumpdb
[https://www.linuxuprising.com/2018/09/easily-format-usb-flash-drive-on-ubuntu.html Easily Format A USB Flash Drive On Ubuntu 18.04 Using USB Stick Formatter] (mintStick [http://packages.linuxmint.com/pool/main/m/mintstick/ deb] & [https://github.com/linuxmint/mintstick source])


# 6. Display Live Network Statistics
This is a GUI application. After the installation, search "USB Stick Formatter".
vnstat -l


# 7. Change the default vnstat output format
For some reason, it doesn't have the 'exFAT' option. My system has installed exFAT drivers. This [https://askubuntu.com/questions/370398/how-to-get-a-drive-formatted-with-exfat-working post] said installing exFAT related drivers only helps reading/writing but not formatting.
vnstat -s (--short)
vnstat --style 0


# 8. Display Top 10 Traffic Days
If I want exFAT format, I need to use the USB Stick Formatter to format the drive first (for example fat32), plug it and then using the following command to format it to exFAT.
vnstat --top10
{{Pre}}
</syntaxhighlight>
sudo apt install exfat-fuse exfat-utils # ubuntu 20.04 and lower
sudo apt install exfat-fuse exfatprogs # ubuntu 22.04 and higher


=== Network related linux commands ===
sudo fdisk /dev/sdc  # g,p,n,p,1,ENTER,ENTER,w
==== ifconfig - spoof the hardware address at the software level ====
sudo fdisk -l /dev/sdc # the new partition has Id 83 and Type Linux.  
To change the MAC address temporarily on a '''NIC''' (network interface controller),
<syntaxhighlight lang='bash'>
sudo ifconfig eth0 down
sudo ifconfig eth0 hw ether 00:11:22:33:44:55
sudo ifconfig eth0 up
</syntaxhighlight>
And it seems there is no need to modify /etc/network/interfaces.


For wlan
sudo mkfs.exfat -n Staples /dev/sdc1
<syntaxhighlight lang='bash'>
sudo fdisk -l /dev/sdc # still Linux? but Gparted shows exfat
sudo ifconfig wlan0 down
sudo ifconfig wlan0 hw ether 00:11:22:33:44:55
sudo ifconfig wlan0 up
</syntaxhighlight>


==== ip ====
sudo mount /dev/sdc1 /mnt # to use
It is said [http://www.cyberciti.biz/faq/linux-ip-command-examples-usage-syntax/ '''ip''' is replacing the old '''ifconfig''' command on modern Linux distributions].
</pre>


==== iptables ====
Note that '''fdisk''' or '''sfdisk''' cannot differentiate NTFS/exFAT. But [https://en.wikipedia.org/wiki/Cfdisk cfdisk] or '''GParted''' can.
See the [[#ufw_.28uncomplicated_firewall.29|ufw]] command which provides an easy way to configure iptables.
{{Pre}}
sudo cfdisk /dev/sdX
</pre>


==== route ====
== Create an ext3/ext4 file system on a USB flash drive ==
[http://www.thegeekstuff.com/2012/04/route-examples/ 7 Linux Route Command Examples]
* https://en.wikipedia.org/wiki/Smartmontools. My ubuntu 20.04 has smartctl 7.1 while the latest version is 7.3 (Fedora has it)
* [https://phoenixnap.com/kb/linux-format-disk How to Format Disk Partitions in Linux]
* GUI: using Ubuntu's '''Disks''' utility.


# Display Existing Routes
<pre>
# Adding a Default Gateway
umount /dev/sdb1  (depending on the device of course)
# List Kernel’s Routing Cache Information
lsblk    # check the drive's partition name
# Reject Routing to a Particular Host or Network
sudo mkfs -t ext4 /dev/sdb1
# Make 192.168.3.* Accessible from 192.168.1.*
lsblk -f  # Verify
# Make 192.168.1.* Accessible from 192.168.3.*
# Allow Internet Access ( External World )


==== traceroute ====
sudo mkfs.ext3 /dev/sdb1
<syntaxhighlight lang='bash'>
sudo e2label /dev/sdb1 usbdrive  (change the label)
sudo apt-get install traceroute
traceroute 8.8.8.8
</syntaxhighlight>


On Windows, we can use the '''tracert''' command. For example, '''tracert www.microsoft.com'''.
sudo mkfs.vfat /dev/sdb1  # MS-DOS
</pre>


==== netstat ====
== exFat - cross platform partition format ==
*[[Mac#ExFat:_Best_drive.2Fpartition_format_to_share_data_between_Mac.2C_Linux_and_OS_X|Mac]]
* Gparted cannot create exFAT partition (it is greyed out)
* [http://www.makeuseof.com/tag/exfat-better-different-fat32/ This Trick Makes a USB Drive Work Perfectly With Windows, Mac, Linux, and Anything Else]
* [http://www.howtogeek.com/235655/how-to-mount-and-use-an-exfat-drive-on-linux/ How to Mount and Use an exFAT Drive on Linux] or [http://askubuntu.com/questions/370398/how-to-get-a-drive-formatted-with-exfat-working How to get a drive formatted with exfat working?]
* [https://www.addictivetips.com/ubuntu-linux-tips/format-sd-card-exfat-in-ubuntu/ How to format an SD Card to ExFat in Ubuntu]
{{Pre}}
sudo apt-get install exfat-utils exfat-fuse
# Still need to create a partition (ex. FAT32) first using gparted in order to get it mounted
sudo fdisk -l
sudo mkfs.exfat -n LABEL /dev/sd**  #  LABEL with whatever you want to label your drive


*    -l or --listening shows only the sockets currently listening for incoming connection.
lsblk -f  # verify the partitions, no sudo is needed
*    -a or --all shows all sockets currently in use.
</pre>
*    -t or --tcp shows the tcp sockets.
This should delivery a working exfat file system (read and write support, but not formatting the drives with exfat via Gnome Disks and GParted).
*    -u or --udp shows the udp sockets.
*    -n or --numeric shows the hosts and ports as numbers, instead of resolving in dns and looking in /etc/services.


<syntaxhighlight lang='bash'>
= Add a new user with home directory; list all users =
netstat -ant          # For tcp
<pre>
netstat -peanut        # Easier to remember
adduser xxx
</syntaxhighlight>
</pre>


==== nmap - port scanning & IPs in local network ====
'''adduser''' is better than '''useradd''' since useradd does not create home directory and it does not even ask the password for new user. '''adduser''' will interactively ask user information.
nmap - Network exploration tool and security / port scanner
* http://www.cyberciti.biz/networking/nmap-command-examples-tutorials/
* http://bencane.com/2013/02/25/10-nmap-commands-every-sysadmin-should-know/
* http://www.tecmint.com/nmap-command-examples/
<syntaxhighlight lang='bash'>
sudo apt-get install nmap


nmap 192.168.1.99    # does not require root privileges
To delete the user and home directory, use
                    # used to check open ports
<pre>
deluser --remove-home xxx
</pre>


nmap 192.168.1.*    # show IPs and ports in LAN
To view the user information, type '' '''id USERNAME''' '' or ''cat /etc/passwd''.


nmap -sP 192.168.1.1/24 # show connected IPs (no hostnames?) and MAC addresses
[https://www.howtogeek.com/803907/linux-list-users/ How to List Users in Linux] '''cat /etc/passwd | wc -l'''
nmap -sV 192.168.1.1 # show Daemon name (in VERSION column) together with port number


nmap -T4 -F 192.168.1.99-255 # show connected IPs and open ports
= gzip with multi cores: pigz =
                            # -F means fast
Use '''[http://zlib.net/pigz/ pigz]''' utility. It makes a lot of difference. For example for a 21GB file, gzip can't finish the job after 30 minutes. But pigz only took 7 minutes on a 12-core machine.
nmap -F taichimd.us
nmap -v taichimd.us


nmap -A 192.168.1.1  # Aggressive scan (more output)
According to 'pigz --help', the default threads is the number of online processors, or 8 if unknown.


nmap -p http,ssh,mysql taichimd.us  # scan ports/services
{{Pre}}
                                    # note that mysql will be shown as closed
sudo apt-get install pigz
nmap --open taichimd.us   # scan open ports
pigz -9 FILENAME   # best compression method & convert the file to FILENAME.gz


sudo nmap -traceroute nih.gov
tar cf - paths-to-archive | pigz -9 -p 12 > archive.tar.gz
</pre>
There is no need to use '''pigz''' to un-compress the file. '''gunzip''' is fast enough and only takes 4 minutes to decompress.


sudo nmap -sS -O 192.168.1.99 # -O shows operating system
The '-9' (best compression) option does not make difference (6.6G vs 6.5G).
                              # eth0 MAC
</syntaxhighlight>


A gui version of nmap is called '''[https://nmap.org/zenmap/ Zenmap]'''.
Note that we have to be careful when we use md5sum to compare compressed files.


==== arp (Address Resolution Protocol) ====
= Compress a folder without full path name =
The '''arp ''' command can be used to show the MAC addresss of all hosts in LAN
Suppose we want to compress the folder ~/Documents and its subfolders. We want to include Documents folder name but not /home/brb/Documents name.
<syntaxhighlight lang='bash'>
{{Pre}}
arp -a
# Method 1. Include 'Documents' as the top folder name
</syntaxhighlight>
cd ~/
tar -czvf tmp.tar.gz Documents
# Method 2. Mind the last dot. Not include 'Documents' as the top folder.
tar -czvf tmp.tar.gz -C /home/brb/Documents .
 
# Double check the tarball
tar -tzvf tmp.tar.gz 
</pre>
 
If we want to strip the upper directories when we uncompress a tar file, use '''--strip-components'''. For example, we can use '''--strip-components=1''' to remove the Documents folder.


=== Copy text to a clipboard to be used in other apps ===
= Fix mess created by accidentally untarred files in the current dir =
Install the '''xclip''' program. See [http://www.cyberciti.biz/faq/xclip-linux-insert-files-command-output-intoclipboard/ here] or [http://stackoverflow.com/questions/5130968/how-can-i-copy-the-output-of-a-command-directly-into-my-clipboard here].
Suppose I accidentally untar a tarball in /var/www/html/ directory instead of /home/projects/www/current. It created mess in /var/www/html/. [https://www.cyberciti.biz/open-source/command-line-hacks/20-unix-command-line-tricks-part-i/ The easiest way to fix this mess]:
<pre>
<pre>
sudo apt-get install xclip
cd /var/www/html/
# Example
/bin/rm -f "$(tar ztf /path/to/file.tar.gz)"
sort -n -k 3, -k 2 file.txt | xclip -selection clipboard
## or better ##
tar ztf /path/to/file.tar.gz | xargs -d'\n' rm -v
</pre>
</pre>
Works.


=== Start Emacs without X ===
= lzma =
Add '''-nw''' (no window) option.
* https://en.wikipedia.org/wiki/Lempel–Ziv–Markov_chain_algorithm
* [https://nomadbsd.org/download.html nomadBSD]. Since NomadBSD is designed to be a persistent system, we do not provide ISO files, as ISO-9660 is a read-only filesystem.
 
= squashfs =
[[Filesystem|squashfs]]
 
= List contents of tar.gz or tar.bz2 =
<pre>
<pre>
emacs -nw
tar -tzvf myfile.tar.gz
 
tar -tjvf myfile.tar.bz2  # replace z with j
</pre>
</pre>


=== mp3 codecs ===
== gzip: stdin: not in gzip format ==
https://help.ubuntu.com/community/RestrictedFormats
I got the following message when I try to run tar -xzvf or tar -tzvf command.
<syntaxhighlight lang='bash'>
<pre>
sudo apt-get install ubuntu-restricted-extras
$ tar -tzvf filename.tar.gz
</syntaxhighlight>
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
$ file filename.tar.gz
filename.tar.gz: POSIX tar archive
</pre>
The answer is [https://itsfoss.com/how-solve-stdin-gzip-format/ How to solve: stdin: not in gzip format].


=== Reduce the size of an mp3 file ===
Solution: Since it was not a gzipped file, a simple tar is able to extract the file: ''tar xvf MyFile.tar.gz ''
Specify a new lower bitrate using the -b option in '''lame'''. For example if your starting mp3 has a quality of 256kbs you can lower its bitrate to 128kbps (or even lower like 64kbps) by:
<syntaxhighlight lang='bash'>
lame --mp3input -b 128 input.mp3 output.mp3
</syntaxhighlight>


=== Audio ===
= Extract files, AVFS =
==== Convert ogg to mp3 ====
See [[Extract_files|Extract files]].
'''ffmpeg''' is not included in Ubuntu repository. Use the '''avconv''' command. http://superuser.com/questions/15327/how-to-convert-ogg-to-mp3
<syntaxhighlight lang='bash'>
sudo apt-get install libav-tools
avconv -i input.ogg -c:a libmp3lame -q:a 2 output.mp3
</syntaxhighlight>


==== Normalize the volume of an audio file ====
= Show folder size for one level only =
* Use [http://www.thebest3d.com/audacity/tutorials/make-louder/audacity-tutorial-make-louder-more-volume-increased-amplitude.html Audacity]. To raise (Amplify) volume: 1. Edit > Select All. 2. Effect > Amplify. Increase db from 0 to 15, for example. Check clip3. Export > MP3 or just start to listen.
<pre>
* Command line tool: [https://libav.org/avconv.html avconv] (replace '''ffmpeg''' program). See [http://gfxile.net/z/?p=1343 this post].
du --max-depth=1 -h
<syntaxhighlight lang='bash'>
</pre>
avconv -ss 00:00:10 -i OLD.mp3 -vol 2560 NEW.mp3
The graphical tool is called '''Disk Usage Analyze''' which is already available on Ubuntu.
</syntaxhighlight>
The anconv/ffmpeg -vol parameter amplifies the sound. The default value is 256 (no amplification), and you can adjust the number accordingly. Here it’s 2560, as it’s 10 times louder. Note that these are not decibel values or anything that sophisticated, but just an integer value. 512 equals to twice the volume, 768 three times, 1024 four times, etc. The -ss parameter specifies the start time offset. Here it will skip the first 10 seconds.
* Command line tool: [http://sox.sourceforge.net/ sox].
** http://askubuntu.com/questions/246242/how-to-normalize-sound-in-mp3-files
** http://www.linuxandlife.com/2013/03/how-to-use-sox-audio-editing.html
** http://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/ deal with several kinds of silence.
** http://www.thegeekstuff.com/2009/05/sound-exchange-sox-15-examples-to-manipulate-audio-files/
I found the converted file by sox has about one half file size compared to anconv/ffmpeg program (source file=47MB, anconv converted=135MB, sox converted file=54MB).
<syntaxhighlight lang='bash'>
sudo apt-get install sox libsox-fmt-all
sox --norm OLD.mp3 NEW.mp3 trim 10
sox --norm OLD.mp3 NEW.mp3 silence 1 0.1 1%
sox -v 4.0 OLD.mp3 NEW.mp3            # increase volume
</syntaxhighlight>
where '--norm' will normalize the audio and the 'trim' option set to skip the first 10 seconds. The silence parameter allows to trim silence at the beginning without a need to specify the number of seconds.


=== Wireshark ===
= Soft link and hard link =
* http://www.howtogeek.com/204458/why-you-shouldn%E2%80%99t-use-mac-address-filtering-on-your-wi-fi-router/
== Soft link ==
* http://www.howtogeek.com/191482/how-an-attacker-could-crack-your-wireless-network-security/
* http://www.howtogeek.com/104278/how-to-use-wireshark-to-capture-filter-and-inspect-packets/
<pre>
<pre>
sudo apt-get install wireshark
ln -s /full/path/of/original/file /full/path/of/soft/link/file
sudo chmod 4711 `which dumpcap`
</pre>
</pre>
Understanding Linux Links [https://www.linux.com/blog/intro-to-linux/2018/10/linux-links-part-1 Part 1] & [https://www.linux.com/blog/2018/10/understanding-linux-links-part-2 Part 2]


=== Track the Time a Command Takes ===
The order of original and linked above in '''ln -s''' is similar to the '''mount''' command where we put the original volume first and the system's directory second. See an example [[Linux#USB_drive|here]].
==== time command ====
 
Use [http://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1 time] command.
But when we issue "ls -l" we see it list the the original file at the end; e.g.  /full/path/of/soft/link/file -> /full/path/of/original/file.
<syntaxhighlight lang='bash'>
time COMMAND
time (COMMAND1; COMMAND2)
time (COMMAND1 && COMMAND2)


help time
== Hard link ==
</syntaxhighlight>
[https://unix.stackexchange.com/a/65003 What's the difference between a hard links and copied files?]


When I run a set of 7 jobs using parallel, time command gives an output
* [https://askubuntu.com/a/525129 Why are hard links not allowed for directories?]
<pre>
* Hard linked file looks the same as the source file when viewed by "ls"
real  15m53.788s
* Change in either of hard linked file and the source file will affect the other
user  95m20.238s
* Hard linked file and source file can be deleted separately without affecting the other
sys  9m1.320s
{{Pre}}
echo "abcd" > foo
ln foo foo2
ls -l foo*
echo "efgh" >> foo2
cat foo
rm foo
cat foo2
</pre>
</pre>
Here we see the real time is about 16m and the user time is about 6-7 times the real time. Indicating the parallel executing works.


==== /usr/bin/time command ====
= Self-hosted servers =
'''[http://man7.org/linux/man-pages/man1/time.1.html /usr/bin/time]''' provides more information then ''time'' command.
* https://github.com/Kickball/awesome-selfhosted This is a list of Free Software network services and web applications which can be hosted locally. Selfhosting is the process of locally hosting and managing applications instead of renting from SaaS providers.
<syntaxhighlight lang='bash'>
* [https://github.com/sovereign/sovereign Sovereign]: A set of Ansible playbooks to build and maintain your own private cloud: email, calendar, contacts, file sync, IRC bouncer, VPN, and more.
man time
 
</syntaxhighlight>
== Cockpit: manage and monitor my servers using just a web browser ==
* https://cockpit-project.org/
* https://localhost:9090 is the default interface
* [https://fedoramagazine.org/cockpit-overview/ Cockpit: an overview]
* [https://fedoramagazine.org/cockpit-and-the-evolution-of-the-web-user-interface/ Cockpit and the evolution of the Web User Interface]
* [https://opensource.com/article/20/11/cockpit-server-management How I use Cockpit for my home's Linux server management]
* [https://www.techrepublic.com/article/how-to-add-public-ssh-keys-for-users-in-cockpit/ How to add public SSH keys for users in Cockpit]
* [https://www.howtogeek.com/702841/how-to-manage-linux-servers-with-the-cockpit-web-interface/ How to Manage Linux Servers with the Cockpit Web Interface] including Monitoring Multiple Computers.


=== Magazines ===
= DNS =
* [http://www.linuxuser.co.uk/ Linux User & Developer]
[[DNS|DNS]]
* [http://www.linuxformat.com/ Linux Format]
* [http://www.linux-magazine.com/ Linux Magazine]
* [http://www.linuxjournal.com/ Linux Journal]


=== PDF reader ===
Port number is 53. An example is [[Raspberry#Pi-hole|Pi-hole]].
The default one '''Evince''' seems slow when I try to view odroid magazine. I installed and tried '''[http://www.mupdf.com/ MuPDF]''' ([https://github.com/muennich/mupdf github] source code). It seems faster and I don't see blank pages when I view one odroid magazine. In terms of speed, mupdf >> xpdf >> okular >> Evince.


<syntaxhighlight lang='bash'>
= Email server =
sudo apt-get install mupdf
See [[Mail_server|Mail_server]].
</syntaxhighlight>
Other choices are
* acroread
* xpdf
* okular (KDE/Qt application), allow to change its [http://askubuntu.com/questions/472540/is-there-a-pdf-reader-allowing-me-to-change-background-color-of-arxiv-pdfs background color]
* kpdf
* gv
* qpdfview
* Foxit or PDF-XChange Viewer(needs wine)


=== PDF highlight and annotation ===
= Backup =
Install [https://docs.kde.org/stable/en/kdegraphics/okular/annotations.html Okular] by
See [[Backup|Backup]].
<pre>sudo apt-get install okular</pre>


To highlight a line, click F6 (Tools -> Review) to turn on the annotation tool bar (it will be shown on the left hand side of the documentation). You can then click
= at command: Schedule a task =
# the 4th icon to highlight a line (it may not be able to select the right texts we want. But when it works the result is nice)
* [https://opensource.com/article/21/8/linux-at-command Schedule a task with the Linux at command]
# the last icon to draw an ellipse or a rectangle (to change from an ellipse to a rectange you can click Settings -> configure Okular... -> annotation)
* [https://linuxhandbook.com/at-command/ Schedule Jobs in Linux With 'at' Command]
* [https://opensource.com/article/21/7/alternatives-cron-linux?utm_source=pocket_mylist 4 alternatives to cron in Linux]
* On Debian, I need to run '''sudo apt install at'''.  
* [https://www.networkworld.com/article/972036/using-the-at-command-to-schedule-tasks-on-linux.html Using the at command to schedule tasks on Linux]
<pre>
$ echo "rsync -av /home/tux/ me@myserver:/home/tux/" | at 1:30 AM


Another method is to use a windows program and run it using Wine. See the discussion [http://askubuntu.com/questions/36696/foxit-reader-on-wine-runs-but-does-not-install here].
$ echo "command_to_be_run" | at 09:00


=== Clock ===
$ atq  # list of jobs
==== xclock ====
<syntaxhighlight lang='bash'>
oclock -geometry 500x500+100+0 &
</syntaxhighlight>


==== oclock ====
$ atrm 6  # delete the 6th job
<syntaxhighlight lang='bash'>
</pre>
oclock -bg blue -geometry 500x500+100+0 -bd purple -transparent &
oclock -bg blue -geometry 500x500+100+0 -bd purple -jewel green &
</syntaxhighlight>
See [http://manpages.ubuntu.com/manpages/hardy/man1/oclock.1.html oclock], [http://manpages.ubuntu.com/manpages/hardy/man7/X.7.html X - a portable, network-transparent window system] which includes an example of specifying the ''geometry'' parameter.


==== dclock ====
= Cron job by root =
Digital clock for the X Window System with flexible display.
Note that there is a "user" field for cron jobs defined in /etc/crontab or /etc/cron.d.
<ul>
<li>Place one: '''/etc/crontab''' and '''/etc/cron.daily, /etc/cron.hourly, /etc/cron.monthly, /etc/cron.weekly'''.  
<pre>
<pre>
sudo apt-get install dclock
cat /etc/crontab
dclock -h
# How to List Daily Cron Jobs
dclock -d
ls -la /etc/cron.daily
dclock -date "Today is %A %B %Y" -geometry 577x194+119+139
</pre>
</pre>


=== wine and winetricks ===
<li>Place two: '''/etc/cron.d'''. It contains "anacron" and "e2scrub_all" on my Debian 11. See [https://superuser.com/a/170870 How to run a cron job as a specific user?]
* https://www.howtoforge.com/tutorial/how-to-use-winetricks/
</ul>


=== Running Linux in the AWS/Amazon Web Services ===
= Running a cron job as a user =
* http://www.linuxuser.co.uk/tutorials/run-linux-in-the-aws-cloud
== Some examples ==
 
* http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
=== Forum software ===
* https://crontab.guru/examples.html and [https://crontab.guru/tips.html tips]
* [http://www.simplemachines.org/ Simple Machines® Forum (SMF)]. For example http://pibot.org/forum/
* Can I break a line cron command into multiple lines? No. Creating another script file in this case.
 
* A specific time
=== RAID ===
{{Pre}}
* http://www.maximumpc.com/what-every-pc-builder-should-know-about-raid-levels/
MIN HOUR DOM MON DOW CMD
30 08 10 06 * $HOME/full-backup >> $HOME/myscript.log 2>&1; echo "Executed at $(date)\n----------" >> $HOME
/myscript.log
#  30 – 30th Minute
#  08 – 08 AM
#  10 – 10th Day
#  06 – 6th Month (June)
#  * – Every day of the week
</pre>
* Twice a day
<pre>
00 11,16 * * * /home/ramesh/bin/incremental-backup
#    00 – 0th Minute (Top of the hour)
#    11,16 – 11 AM and 4 PM
#    * – Every day
#    * – Every month
#    * – Every day of the week
</pre>
* Every 10 minutes
<pre>
*/10 * * * * /home/ramesh/check-disk-space
</pre>
* [https://unix.stackexchange.com/a/16094 Every odd day or even day]
<pre>
# Will only run on odd days:
0 0 1-31/2 * * command


=== Timer ===
# Will only run on even days:
* http://zeegaree.com/. Require 3 libraries that we need to install them using apt-get install. See the [https://github.com/mivoligo/Zeegaree#zeegaree github] page.
0 0 2-30/2 * * command
</pre>


=== How to track you laptop using Prey ===
== crontab ==
https://www.howtoforge.com/tutorial/how-to-track-your-linux-laptop/
* [https://www.makeuseof.com/how-to-use-crontab-linux/ How to Use Crontab to Automate Repetitive Tasks in Linux]. Some examples: play sound, backup files, check if sites are online.
* [https://www.ubuntupit.com/amazing-linux-crontab-commands-for-the-sysadmins/ 50 Amazing Linux Crontab Commands For The SysAdmins]
<pre>
crontab SOME-CRON-FILE; crontab -l
</pre>


=== Automatic reboot after power failure ===
Make sure the .sh file gives a complete path. For example,
It seems there is no reliable way to find out when the power failed.
<pre>
 
#!/bin/sh
The linux command 'last' can show some information about system reboot.
R --vanilla  < arraytoolsip.R
</pre>
does not work in cron job although it works perfect when we manually run it from the right path. The sh file should be
<pre>
#!/bin/sh
R --vanilla  < $HOME/Dropbox/scripts/arraytoolsip.R
</pre>


Another way is to modify the BIOS to select the option like 'Power off and Reboot'. This won't automatically boot your computer when it is shutdown normally.
To disable everything on ''crontab -l'', use one of the following methods:
* run ''crontab -e'' then comment out each line you don't want to run with #. OR
* run ''crontab -r'' to empty the current crontab. OR
* run ''crontab'' with no arguments, and then type Ctrl+D. It will create an empty crontab, overwriting your previous crontab.


=== Speedtest-cli ===
== GUI ==
See [[Raspberry#Track_Internet_Dropouts|Track_Internet_Dropouts]].
[https://www.linuxuprising.com/2020/10/schedule-commands-and-scripts-in-linux.html Schedule Commands And Scripts In Linux With Zeit (GUI For Cron And At)]


<syntaxhighlight lang='bash'>
== PATH and Shell ==
sudo apt-get intall python-pip
Cron knows nothing about your shell; it is started by the system, so it has a minimal environment. If you want anything, you need to have that brought in yourself. For example, to use 'ifconfig' command, I need to give it a complete path in my script file.
sudo pip install speedtest-cli
{{Pre}}
# A slightly modified code that will create a one-line space/semi-colon
$ cat syncIP
# delimited result is
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
git clone https://github.com/HenrikBengtsson/speedtest-cli-extras.git
</pre>
and the cron job
<pre>
06 15 * * * /home/MYUSERNAME/Ubuntu\ One/syncIP > $HOME/Ubuntu\ One/ip.txt 2>&1
</pre>
See [http://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables here] on how to add environment variable into cron environment.


speedtest-cli-extras/bin/speedtest-csv
== Disable mail alert ==
</syntaxhighlight>
If something went wrong with executing a cron job, cron will output a message "You have new mail in /var/mail/$USER". You can open this file using a text editor. To disable this alert, run ''''crontab -e''' (see [http://www.cyberciti.biz/faq/disable-the-mail-alert-by-crontab-command/ this post])
works. But if I want to put it in cron, cron will issue an error speedtest-cli cannot be found. So I need to modify line 52 of the code in <speedtest-cli-extras/bin/speedtest-csv> to explicitly specify the location of speedtest-cli.
<pre>
<pre>
    /usr/local/bin/speedtest-cli --share > $log
0 1 5 10 * /path/to/script.sh >/dev/null 2>&1
# OR
0 1 5 10 * /path/to/script.sh > /dev/null
</pre>
</pre>
Another way is to add '''MAILTO=""''' at the top of the crontab file.


NOTE: 1. the results differ from the network connection. For example, the speed is good when I test it on the machine directly connected to the router. 2. It is helpful to modify the last line of the bash script to output what I need. 3. The separator is ";" in the output.
== Run a command at boot ==
* [https://www.2daygeek.com/execute-run-linux-scripts-command-at-reboot-startup/ How to Execute a Command or Script at Reboot or Startup]
*# Run Script or Command at Reboot or Startup Using /etc/rc.d/rc.local File
*# Execute a Command or Script at Reboot or Startup Using the crontab
*# Run a Command or Script at Reboot or Startup Using the systemd service unit
<ul><li>[[Raspberry#Sending_an_email_on_boot|Sending an email on boot]]
<pre>
@reboot sleep 300 && python /home/pi/startup_mailer.py
</pre>
</li>
<li>[https://github.com/martinwoodward/PumpkinPi pausing for 10 seconds before running the python script]
<pre>
@reboot /bin/sleep 10 ; /usr/bin/python /home/pi/PumpkinPi/src/pumpkinpi.py &
</pre>
</li>
</ul>


=== Linux Logo and the current system information ===
=== rc.local ===
* http://www.cyberciti.biz/hardware/howto-display-linux-logo-in-bash-terminal-using-screenfetch-linux_logo/
[https://www.cyberciti.biz/faq/how-to-enable-rc-local-shell-script-on-systemd-while-booting-linux-system/ How to enable rc.local shell script on systemd while booting Linux system]


<syntaxhighlight lang='bash'>
= Running crontab as root =
odroid@odroid:~$ sudo apt-get install screenfetch
Use '''sudo crontab -e''' to edit. After saving it, no need to initialize it. Use '''sudo crontab -l''' to list the cron job.
odroid@odroid:~$ screenfetch
                          ./+o+-      odroid@odroid
                  yyyyy- -yyyyyy+      OS: Ubuntu 15.10 wily
              ://+//////-yyyyyyo      Kernel: armv7l Linux 3.10.96-77
          .++ .:/++++++/-.+sss/`      Uptime: 4d 23h 8m
        .:++o:  /++++++++/:--:/-      Packages: 2000
        o:+o+:++.`..```.-/oo+++++/    Shell: 2263
      .:+o:+o/.          `+sssoo+/    Resolution: 1920x1080
  .++/+:+oo+o:`            /sssooo.  DE: MATE 1.10.2
/+++//+:`oo+o              /::--:.  WM: Metacity (Marco)
\+/+o+++`o++o              ++////.  GTK Theme: 'Ambiant-MATE' [GTK2/3]
  .++.o+++oo+:`            /dddhhh.  Icon Theme: Ambiant-MATE
      .+.o+oo:.          `oddhhhh+    Font: Ubuntu 10
        \+.++o+o``-````.:ohdhhhhh+    CPU: ARMv7 rev 3 (v7l) @ 1.4GHz
        `:o+++ `ohhhhhhhhyo++os:      GPU: Gallium 0.4 on llvmpipe (LLVM 3.6, 128 bits)
          .o:`.syhhhhhhh/.oo++o`      RAM: 537MiB / 1990MiB
              /osyyyyyyo++ooo+++/   
                  ````` +oo+++o\:   
                          `oo++.    


odroid@odroid:~$ screenfetch -s  # take a screenshot and auto save it to ~/ directory.
== Display and back up cron jobs ==
[https://www.cyberciti.biz/faq/linux-show-what-cron-jobs-are-setup/ Linux List / Display and view all cron jobs]


odroid@odroid:~$ sudo apt-get install linuxlogo
== Check log ==
odroid@odroid:~$ linuxlogo
'''sudo grep CRON /var/log/syslog --color'''
        _,met$$$$$gg.                                                         
    ,g$$$$$$$$$$$$$$$P.                                                       
  ,g$$P""      """Y$$.".                                                     
  ,$$P'             `$$$.                                                     
',$$P      ,ggs.    `$$b:                                                   
`d$$'     ,$P"'  .    $$$                              ,#.                   
$$P      d$'    ,    $$P      ##:          :##        :###:                 
$$:      $$.  -   ,d$$'      ##'          `##        `#'                   
$$;      Y$b._  _,d$P'    __  ##    __    ##  __      _    __          _ 
Y$$.    `.`"Y$$$$P"'    ,####:##  ,######.  ##.#####. :### ,######. ###.####:
`$$b      "-.__        ,##' `###  ##:  :##  ###' `###  ##' #:  `## `###' `##:
  `Y$$b                  ##    `##  ##    ##  ##'  `##  ##    ___,##  ##:  `##
  `Y$$.                ##    ##  #######:  ##    ##  ##  .#######  ##'    ##
    `$$b.              ##    ##  ##'      ##    ##  ##  ##'  `##  ##    ##
      `Y$$b.            ##.  ,##  ##        ##    ,##  ##  ##    ##  ##    ##
        `"Y$b._        :#:._,###  ##:__,##  ##:__,##' ,##. ##.__:##. ##    ##
            `""""      `:#### ###  ######' `######' #### `#####"## ##    ##


Linux Version 3.10.96-77, Compiled #1 SMP PREEMPT Fri Feb 5 04:47:32 BRST 2016
== Anacron ==
            Eight ARM  Processors, 2GB RAM, 456.00 Bogomips Total
Anacron keeps track of the last time a task was run, and if it was missed, it runs it.
                                    odroid


odroid@odroid:~$ linuxlogo -f -L list
Anacron typically runs daily, while cron runs every minute.
odroid@odroid:~$ linuxlogo -f -L ubuntu
<pre>
              .-.  
cat /etc/anacrontab
        .-'``(|||)
</pre>
    ,`\ \    `-`.                88                        88
    /   \ '``-.  `                88                        88
  .-.  ,      `___:      88  88  88,888,  88  88  ,88888, 88888  88  88
(:::) :        ___      88  88  88  88  88  88  88  88  88    88  88
  `-`  `      ,  :      88  88  88  88  88  88  88  88  88    88  88
    \  / ,..-`  ,      88  88  88  88  88  88  88  88  88    88  88
    `./ /   .-.`        '88888'  '88888'  '88888'  88  88  '8888 '88888'
        `-..-(  )
              `-`


= GUI cron =
* [https://www.ostechnix.com/how-to-easily-and-safely-manage-cron-jobs-in-linux/ How To Easily And Safely Manage Cron Jobs In Linux]
* [https://github.com/alseambusher/crontab-ui Crontab UI]
* http://corntab.com/#!


Linux Version 3.10.96-77, Compiled #1 SMP PREEMPT Fri Feb 5 04:47:32 BRST 2016
= md5sum =
            Eight ARM  Processors, 2GB RAM, 192.00 Bogomips Total
[https://www.howtoforge.com/linux-md5sum-command/ Linux md5sum Command Explained For Beginners (5 Examples)]
                                    odroid


odroid@odroid:~$ screenfetch -h
How to verify files?
odroid@odroid:~$ linuxlogo -h
<pre>
</syntaxhighlight>
md5sum file1.txt file2.txt file3.txt > hashes
md5sum --check hashes
</pre>


=== ASCII art ===
= fsck =
* http://patorjk.com/software/taag/#p=display&f=Ivrit&t=BRR-SeqTools
* [https://www.cyberciti.biz/tips/repairing-linux-ext2-or-ext3-file-system.html Repairing Linux ext2 or ext3 or ext4 File System (fsck)]
<pre>
* [https://www.thegeekstuff.com/2012/08/fsck-command-examples 10 Linux Fsck Command Examples to Check and Repair Filesystem]
  ____  ____  ____      ____            _____          _   
* [https://www.tecmint.com/fsck-repair-file-system-errors-in-linux/ How to Use ‘fsck’ to Repair File System Errors in Linux]
| __ )|  _ \| __ )    / ___|  ___  __ |_  _|__  ___ | |___
* [https://www.maketecheasier.com/repair-mac-hard-disk-with-fsck/ How to Repair Hard Disks with fsck on macOS]
|  _ \| |_) |  _ \ ____\___ \ / _ \/ _` || |/ _ \ / _ \| / __|
* [https://ostechnix.com/fsck-command-examples/ How To Use Fsck Command To Check And Repair Linux File Systems] (2024 Update)
| |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
 
|____/|_| \_\____/     |____/ \___|\__, ||_|\___/ \___/|_|___/
== Fsck error on boot ==
                                      |_|                   
[https://askubuntu.com/questions/697190/fsck-error-on-boot-dev-sda6-unexpected-inconsistency-run-fsck-manually fsck error on boot: /dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY]
</pre>
* http://patorjk.com/software/taag/#p=display&f=Big&t=BRB-SeqTools
<pre>
  ____  _____  ____        _____        _______          _   
|  _ \|  __ \|  _ \      / ____|      |__  __|        | |   
| |_) | |__) | |_) |____| (___  ___  __ _| | ___  ___ | |___
|  _ <|  _  /|  _ <______\___ \ / _ \/ _` | |/ _ \ / _ \| / __|
| |_) | | \ \| |_) |    ____) |  __/ (_| | | (_) | (_) | \__ \
|____/|_|  \_\____/    |_____/ \___|\__, |_|\___/ \___/|_|___/
                                        | |                   
                                        |_|                   
</pre>
* http://patorjk.com/software/taag/#p=display&f=Small&t=BRB-SeqTools
<pre>
  ___ ___ ___    ___          _____        _   
| _ ) _ \ _ )___/ __| ___ __ |_  _|__  ___| |___
| _ \  / _ \___\__ \/ -_) _` || |/ _ \/ _ \ (_-<
|___/_|_\___/   |___/\___\__, ||_|\___/\___/_/__/
                            |_|                 
</pre>


=== Software that scan Malware and rootkits ===
This happened when I resize an Ubuntu partition.  
* https://www.howtoforge.com/tutorial/how-to-scan-linux-for-malware-and-rootkits/


=== Text to speech ===
fsck -fy /dev/sda1
* http://www.eguidedog.net/ekho.php. Compilation/build works on x86 Ubuntu 14 and Odroid Ubuntu 15.10. On Odroid I have to follow their instruction to use 'make CXXFLAGS=-DNO_SSE' instead of 'make'. However, sound feels shaky on Odroid xu4.
* http://audiobookmaker.com/
* http://project-modelino.com/online-resources-category.php?site_language=english&learn_language=chinese&category=tts


== Debian/Ubuntu/Bio-Linux ==
== Force fsck on the Next Reboot or Boot Sequence ==
https://www.linuxuprising.com/2019/05/how-to-force-fsck-filesystem.html


=== Debian ===
https://www.cyberciti.biz/faq/linux-force-fsck-on-the-next-reboot-or-boot-sequence/ Create a blank file ''/forcefsck'' and '''fsck''' will check your drive next time your reboot.
==== Download Debian ====
{{Pre}}
Go to http://www.debian.org/distrib/ and download "Small CDs or USB sticks", for example ''debian-8.1.0-amd64-netinst.iso'' (Jessie, released June 2015). It is about 280 MB.
sudo touch /forcefsck
</pre>


Screenshots of step-by-step installation can be found in [http://debian-handbook.info/browse/wheezy/sect.installation-steps.html here].
The fsck was used to fix a [https://ext4.wiki.kernel.org/index.php/Ext4_Metadata_Checksums#Journal journal checksum] error on a USB drive which has been formatted as Ext4 was used on a security camera application; see [[Raspberry#Security_Camera:_motion_and_motionEyeOS|motionEyeOS]].


At the end of installation, it will offer a collection of software to install. Below 'Debian desktop environment', it has a selection of GNOME, Xface, KDE, Cinnamon, MATE and LXDE (new in Jessie/8.0). Note that the [http://cdimage.debian.org/debian-cd/8.0.0/amd64/bt-cd/ cd images download page] only provides a selection of kde, lxde and xfce desktop. The default is 'GNOME' in Jessie.
== Can I run fsck or e2fsck when Linux file system is mounted? ==
https://www.cyberciti.biz/faq/can-i-run-fsck-or-e2fsck-when-linux-file-system-is-mounted/


[[File:DebianInstall.png|200px]]
== What is the difference between fsck and e2fsck? ==
https://superuser.com/a/19984


After installation, you got a desktop environment of Debian based on GNOME 3 (Virtual machine will use recovery mode, but still works. Some people suggest to install the guest additions (in the guest) and make sure that you enable the 3D acceleration in the guest settings.). Also 'free -m' command shows it uses 202 MB memory and the whole system takes up 3.3 GB. I am testing on a Chinese desktop environment.
= Swap partition =
* [https://www.howtogeek.com/455981/how-to-create-a-swap-file-on-linux/ How to Create a Swap File on Linux]
* [https://www.tecmint.com/disable-swap-partition-in-centos-ubuntu/ How to Permanently Disable Swap in Linux]


When Debian is in recovery mode, the desktop interface is like old fashion. Application and Place on top of the screen. When GNOME 3 is working (in my test of Debian 7.1.0, I cannot run VBoxLinux.run, but it still works after I did other steps), the interface is sort of Ubuntu with application launched from the left hand side. It differs from Ubuntu because the side bar appears by clicking a 'preview' button on top left corner.
== Swap file vs swap partition ==
[https://www.jetsonhacks.com/2019/04/25/jetson-nano-run-on-usb-drive/ Jetson Nano – Run on USB Drive]


The default browser in Debian is Iceweasel with AdBlock Plus preinstalled.
= Mount drive, add a new hard drive =
* [https://www.cloudsavvyit.com/3349/how-to-add-a-new-drive-to-your-existing-linux-server/ How To Add a New Drive to Your Existing Linux Server]
* Videos
** [https://youtu.be/2Z6ouBYfZr8 Linux Crash Course - Formatting & Mounting Storage Volumes]
** [https://youtu.be/A7xH74o6kY0 Linux Crash Course - The /etc/fstab file]


I don't know why the default user does not have root privilege.
== /etc/fstab and blkid ==
See [[Fstab]].


When I installed the Chinese version, the keyboard switch icon (SCIM) is automatically available. However once the desktop is in regular GNOME 3, the switch icon disappeared. Fortunately, we can use Ctrl + Space to switch languages. Thanks to the [http://verahill.blogspot.com/2012/01/debian-testing-64-wheezy-chinese.html hint] there.
== autofs, /etc/auto.master ==
[https://opensource.com/article/18/7/network-attached-storage-Raspberry-Pi Building a network attached storage device with a Raspberry Pi]


==== Server version ====
== Fix a malfunctioning USB device or port ==
There is no a server version of iso to download. At the end of installation, it will ask what software to install: Debian desktop environment, Web server, SSH server, Laptop, SQL database, ... We can uncheck 'Debian desktop environment' item.
[https://www.makeuseof.com/tag/fix-usb-device-port-linux/ 5 Ways to Fix a Malfunctioning USB Device or Port on Linux]


Compared to Desktop version, the server version takes 1.3GB space and 33MB memory.
== Check the physical health of a USB stick ==
[https://www.cyberciti.biz/faq/linux-check-the-physical-health-of-a-usb-stick-flash-drive/ Linux check the physical health of a USB stick]


The server version does not have 'sudo' command. Use 'su' to switch to 'root' user.
== USB drive ==
* [https://help.ubuntu.com/community/RenameUSBDrive Rename USB drive partition '''label''']. It seems if a device does not have a label, Ubuntu will use its 32-digit UUID as the mount point (eg. '''/media/$USER/$Long_UUID'''). This is very cumbersome. To fix that, we can open the '''Disks''' utility and select the partition of the device. Click the two-gear icon and pick '''Edit Filesystem...''' where we can change the filesystem '''label'''. After that, we can reject the USB and re-plug it to see the new mount directory based on the new label we specified ('''/media/$USER/$Label'''). We can also use the command '''lsblk''' (no sudo needed) to check.
* If I use "GParted" utility to check the "partition '''name''' ", it is not the same as the name I just specified through the "Disks" utility. But the "Information" window give a complete data. It is a little confusing that the partition label becomes the filsystem label and the Partition name shown on GParted was different & seems not to be used.
[[File:GpartedinfoSanDisk.png|250px]]
* [https://askubuntu.com/a/113746 How do I correctly mount a NTFS partition in /etc/fstab?]


Note that even we installed 'sudo', we can not use 'sudo' from the default user. It will complain '''xxx is not in the sudoers file. This incident will be reported.'''.
Run the following to confirm the USB device is detected.  
{{Pre}}
sudo fdisk -l
# OR
dmesg | grep -i "SCSI"
</pre>


==== Virtualbox guest addition installation ====
Now suppose the usb device is found in '''dev/sdb1'''.
See [[Virtualbox#Debian|Virtualbox -> Debian]].
{{Pre}}
sudo mkdir /mnt/usb
sudo mount -t vfat -o rw,users /dev/sdb1 /mnt/usb
</pre>
The above mount command assumes the usb drive has Windows vfat partition and ''users'' give non-root users the ability to unmount the drive.
If the USB drive is partitioned linux ext2/3, we can merely run mount command as
{{Pre}}
sudo mount /dev/sdb1 /mnt/usb
</pre>


==== Browse iso files ====
At the end, run umount command like
Note that if we want to download the iso image, we should consider using the torrent method.
{{Pre}}
The can see a variety of download options from
sudo umount /mnt/usb
</pre>


http://www.debian.org/CD/ > Downloading Debian CD/DVD images via HTTP/FTP
To make the mounting automatically, edit the file '''/etc/fstab'''.
<pre>
/dev/sdb1      /mnt/usb          vfat    defaults        0      0
/dev/sdb2      /mnt/usb2          ext3    defaults        0      0
UUID=XXXXXXXXXX /mnt/usb3      ntfs-3g    rw              0      0
</pre>
and run
{{Pre}}
sudo mount -a
</pre>


* (Official) http://cdimage.debian.org/debian-cd/8.0.0/amd64/iso-cd/
== Mount an iso file ==
* (One of mirrors in US) http://mirrors.kernel.org/debian-cd/8.0.0/amd64/iso-cd/
* http://www.shellhacks.com/en/Mounting-an-ISO-Image-in-Linux
{{Pre}}
sudo mkdir -p /mnt/mount_point # create a mount point
sudo mount -o loop /home/user/disk.iso /mnt/mount_point
mount  # verify
</pre>


==== Permission denied ====
== Mount remote Windows share ==
http://roger.steneteg.org/blog/virtualbox-guest-additions-on-debian/
* http://www.shellhacks.com/en/HowTo-Mount-Remote-Windows-Partition-Share-under-Linux


The script uses /bin/sh as shell and on Debian Wheezy/Jessie /bin/sh is symlinked to /bin/dash. Dash is a more light-weight replacement for Bash, and it turns out that the VirtualBox script does not work as it should when run with "dash".
== Sharing files with Windows by using NitroShare ==
[http://www.ubuntugeek.com/simple-way-of-sharing-files-between-ubuntu-16-04-and-windows-10.html Simple way of Sharing files between Ubuntu 16.04 and Windows 10] by using open-source [https://nitroshare.net/ NitroShare] which is based on Qt framework.


An easy workaround is to explicitly run the script with "bash" with the following command:
== NTFS usb drive in xubuntu ==
http://xflinux.blogspot.com/2011/01/mount-ntfs-volumes-automatically-in.html
<pre>
<pre>
sudo bash ./VBoxLinuxAdditions.run
sudo apt-get install ntfs-config
</pre>
</pre>
Now go to Applications>> System>> Ntfs Configuration Tool


==== Browse source code ====
Expand the "Advanced Configuration" and select all those partitions you want to be auto mounted and writable( The tool will detect all partitions at its startup).
* http://archive.ubuntu.com/
* https://wiki.ubuntu.com/Kernel/SourceCode
* [[Linux#Count_number_of_rows_in_a_file_-_wc|Find a command's package name]]
* https://stackoverflow.com/questions/4767821/how-do-i-get-the-ubuntu-source-code


=== Ubuntu/Kubuntu/Lubuntu/Xubuntu ===
Make sure the " Enable write support for internal devices" option is selected. Now click Close.
Download links for all versions from [https://wiki.ubuntu.com/ wiki.ubuntu.com] > [http://releases.ubuntu.com/ releases.ubuntu.com].


Ubuntu [https://wiki.ubuntu.com/UbuntuFlavors flavors] and [http://www.ubuntu.com/about/about-ubuntu/derivatives derivatives]
== Many drives, one folder ==
* [http://www.linuxjournal.com/content/many-drives-one-folder mhddfs] program.
 
== Partition tables ==
[http://www.makeuseof.com/tag/partition-table-edit-error/ Partition Tables and the Dangers of Editing Them]
 
== parted command ==
[https://opensource.com/article/18/6/how-partition-disk-linux How to partition a disk in Linux]
 
== Recommended partition schemes ==
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s2-diskpartrecommend-x86.html Redhat]
* [https://www.debian.org/releases/stable/i386/apcs03.html.en Debian]
* [https://help.ubuntu.com/community/PartitioningSchemes Ubuntu]
* [https://www.centos.org/docs/5/html/5.2/Installation_Guide/s2-diskpartrecommend-s390.html CentOS]
* [https://wiki.archlinux.org/index.php/partitioning#Discrete_partitions Arch] Linux


For some reason, when I try the Ubuntu (13.04) live CD, the screen resolution looks perfect. But when I installed the OS, the screen resolution is always too low. The propriety graphics driver cannot be installed successfully. Fortunately, when I try the Kubuntu (13.04), the display resolution problem automatically works!
== HOME /home directory ==
[https://www.howtogeek.com/442101/how-to-move-your-linux-home-directory-to-another-hard-drive/ How to Move Your Linux home Directory to Another Drive]


Update: Kubuntu failed to respond after I install SCIM related programs. A freshly installed linuxmint OS also has a similar problem that the desktop does not respond to mouse or keyboard. Luckily, the Xubuntu works fine and the Chinese input works out of box if I choose Chinese as desktop environment (339MB was used).
== /var directory filled up ==
[https://linuxconfig.org/how-to-move-var-directory-to-another-partition How to move /var directory to another partition]
{{Pre}}
blkid | grep sdc1  # get UUID
mkdir /mnt/newvar
mount /dev/sdc1 /mnt/newvar
df -h /mnt/newvar
rsync -aqxP /var/* /mnt/newvar  # q=quiet,x=one-file-system, P=partial,progress
umount /mnt/newvar/  /mnt/var/
nano /etc/fstab
# UUID=XXXX  /var    ext4  defaults  0  2
</pre>
Reboot


==== Download mirror ====
== Why put things other than /home to a separate partition? ==
https://launchpad.net/ubuntu/+cdmirrors
[https://unix.stackexchange.com/questions/685/why-put-things-other-than-home-to-a-separate-partition Why put things other than /home to a separate partition?]


==== Installation ====
The /var partition is used by Docker and Apache.
Installing Ubuntu (or xubuntu, Mint) still requires an internet connection for downloading '''language packs'''. ''This could be very time consuming.'' However, in the installation process I can click the 'skip' button to skip downloading language packs. This saves a lot of time when the internet connection is slow. After ubuntu desktop appears, it still pops up a message to give an instruction to install language packs.


The installation takes about 10 minutes when I installed ubuntu 14.04 (unity) on virtualBox.
[https://unix.stackexchange.com/a/84764 /home, /boot and /var partitions] can be separated.


==== End of life date of Ubuntu release ====
= Process/job =
https://wiki.ubuntu.com/Releases


Each time I log into my Ubuntu 12.04.5 LTE, I'll receive a message
== ps and top commands ==
[https://www.howtogeek.com/448271/how-to-use-the-ps-command-to-monitor-linux-processes/ How to Use the ps Command to Monitor Linux Processes],  
[https://www.cyberciti.biz/faq/how-to-check-how-long-a-process-has-been-running/ Linux how long a process has been running?]
<pre>
<pre>
New release '14.04.2 LTS' available.
ps -C shutter # Listing only a Process by Command
Run 'do-release-upgrade' to upgrade to it.
              # Adding the 'watch' command to show the process in real-time
ps -C dd --format pid,cmd,%cpu # Show PID, CMD and %CPU


Your current Hardware Enablement Stack (HWE) is no longer supported
sudo ps -p {PID} -o pid,cmd,lstart,etimes,etime
since 2014-08-07.  Security updates for critical parts (kernel
and graphics stack) of your system are no longer available.


For more information, please see:
ps -e | less # Listing Process for All Users
http://wiki.ubuntu.com/1204_HWE_EOL


There is a graphics stack installed on this system. An upgrade to a
ps -eH --forest | less # hierarchy
supported (or longer supported) configuration will become available
on 2014-07-16 and can be invoked by running 'update-manager' in the
Dash.
</pre>


==== Black screen on boot Ubuntu 14.04 ====
ps -e | grep firefox # Listing Processes by Name
[http://ubuntuforums.org/showthread.php?t=2245141 Press e when you see the first menu].


==== Server version ====
ps -p 3403 # Listing Processes by Process ID
[[File:UbuntuServerInstall.png|150px]]


==== [http://www.bandshed.net/AVLinux.html AV Linux] ====
ps -u mary  # Listing Processes Owned by a User
AV Linux features a complete customized Debian Linux XFCE4 4.10 Desktop Environment with the added bonus of a handpicked selection of pre-tested and pre-configured Audio, Graphics and Video content creation software demonstrating the excellence of Open-Source and also includes many unique Commercial Demos.


==== Kali Linux ====
sudo pkill top # Killing Processes by Name
* http://lifehacker.com/how-to-hack-your-own-network-and-beef-up-its-security-w-1649785071
* https://www.offensive-security.com/kali-linux-vmware-arm-image-download/ In addition to regular linux image, Kali provides images for VirtualBox, VMWARE and ARM devices like Raspberry Pi, Beaglebone Black, Chromebook, Odroid, et al.


==== Create customized ubuntu iso ====
sudo killall top # Killing Multiple Processes by Name
* [http://www.ubuntu-mini-remix.org/ Ubuntu Mini Remix] (~200MB). Note that this is a live ubuntu which can't be installed even we can remaster it to include Desktop Environment, packages, et al. See [https://answers.launchpad.net/ubuntu-mini-remix/+faq/35 this FAQ].
</pre>
** [http://sourceforge.net/projects/uck/ Ubuntu customization kit] - [http://www.linux.com/learn/tutorials/739139-roll-your-own-customized-ubuntu-with-uck linux.com] [http://www.howtogeek.com/109736/how-to-create-a-custom-ubuntu-live-cd-or-usb/ howtogeek]. The project has not been updated since 2013-01-16.
** [https://launchpad.net/ubuntu-builder Ubuntu Builder] - [http://lifehacker.com/5921054/ubuntu-builder-lets-you-build-your-own-customized-linux-distribution lifehacker]. It looks the project is abandoned.
** [https://github.com/fluxer/Customizer Customizer] - quite information from its website. The [https://github.com/clearkimura/Customizer/wiki/Manuals manuals/user guide 3.x] p46 talks about how to make the iso installable instead of just a live CD (e.g. '''apt­-get install ubiquity ubiquity-­frontend-­gtk'''). '''N.B.''' ''Installing [https://en.wikipedia.org/wiki/Ubiquity_(software) ubiquity] should be run once we have installed all software we want; i.e. if we want to install xfce4 we should install xfce4 before we install ubiquity.'' Also for some reason, Customizer crashed when I tried to create an iso if I have installed xubuntu-desktop, ubiquity and ubiquity-­frontend-­gtk.


Note that the Ubuntu Mini Remix by default contains only 3 repositories. We may want to add some more.
== Kill a process and the '''pstree''' command ==
* https://en.m.wikipedia.org/wiki/Pstree
* On Ubuntu docker container, we can need to run ''apt install psmisc'' to get the pstree command.
<ul>
<li>[http://morningcoffee.io/killing-a-process-and-all-of-its-descendants.html Killing a process and all of its descendants]. This covers a '''PPID''', '''PID''' and more importantly '''PGID''', '''SID'''. Also '''ps j -A''' command can show these IDs for the running processes.
{{Pre}}
$ tail -f /var/log/syslog | grep "CRON" &
$ ps j
$ kill -SIGTERM -- -($Some_PGID)
</pre></li>
<li>pgrep & kill
{{Pre}}
# find the PID
pgrep ProgramName
# Kill the ProgramName process
kill -9 PID
</pre>
</li>
<li>'''killall'''. For example, if Firefox is acting up (as Firefox will do from time to time) simply type '''killall firefox''' and it should kill the application completely.
In the rare circumstances that this doesn’t work you can always type '''xkill''' and then click on the window that won’t close; this will completely close a given window immediately. See [http://www.makeuseof.com/tag/5-easier-command-line-linux/ this]. To kill a privileges process, use for example '''sudo killall crond'''.
<pre>
<pre>
deb http://archive.ubuntu.com/ubuntu/ trusty main restricted
sudo killall -u USERNAME
deb http://security.ubuntu.com/ubuntu/ trusty-security main restricted
deb http://archive.ubuntu.com/ubuntu/ trusty-updates main restricted
</pre>
</pre>
while for example an official v14.04 xubuntu contains 22 sources,
</li>
<pre>
</ul>
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
* [http://www.2daygeek.com/kill-inactive-idle-ssh-sessions/ How To kill An Inactive OR Idle SSH Sessions]. The '''pstree -p''' command can show a tree diagram of all the processes.
# newer versions of the distribution.
* [https://www.howtoforge.com/linux-pkill-command/ pkill] command. For example, ''pkill gedit''.
deb http://us.archive.ubuntu.com/ubuntu/ trusty main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty main restricted


## Major bug fix updates produced after the final release of the
== Kill a process running on a specific port ==
## distribution.
[https://linuxtldr.com/kill-a-process-running-on-a-specific-port-in-linux/ Kill a Process Running on a Specific Port in Linux (via 4 Methods)]
deb http://us.archive.ubuntu.com/ubuntu/ trusty-updates main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty-updates main restricted


## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
== How to Kill Zombie Processes on Linux ==
## team. Also, please note that software in universe WILL NOT receive any
[https://www.howtogeek.com/701971/how-to-kill-zombie-processes-on-linux/ How to Kill Zombie Processes on Linux]
## review or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ trusty universe
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty universe
deb http://us.archive.ubuntu.com/ubuntu/ trusty-updates universe
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty-updates universe


## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
== Simulate/produce high cpu load ==
## team, and may not be under a free licence. Please satisfy yourself as to
[https://superuser.com/a/443409 How can I produce high CPU load on a Linux server?]
## your rights to use the software. Also, please note that software in
<pre>
## multiverse WILL NOT receive any review or updates from the Ubuntu
# method 1:
## security team.
sudo apt install stress
deb http://us.archive.ubuntu.com/ubuntu/ trusty multiverse
stress --cpu 3
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty multiverse
deb http://us.archive.ubuntu.com/ubuntu/ trusty-updates multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty-updates multiverse


## N.B. software from this repository may not have been tested as
# method 2:
## extensively as that contained in the main release, although it includes
for i in 1 2 3 ; do while : ; do : ; done & done
## newer versions of some applications which may provide useful features.
jobs  # list background jobs
## Also, please note that software in backports WILL NOT receive any review
for i in 1 2 3 4; do kill %$i; done  # kill "job" (not "PID") 1,2,3,4
## or updates from the Ubuntu security team.
</pre>
deb http://us.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ trusty-backports main restricted universe multiverse


deb http://security.ubuntu.com/ubuntu trusty-security main restricted
== ps, pgrep and pidof: How much resource is used by a process ==
deb-src http://security.ubuntu.com/ubuntu trusty-security main restricted
Find the process ID first by '''ps -ef | grep APPLICATIONAME''' where "-e" is to show the running processes and "-f" is for a full listing. Then
deb http://security.ubuntu.com/ubuntu trusty-security universe
{{Pre}}
deb-src http://security.ubuntu.com/ubuntu trusty-security universe
ps -p <pid> -o %cpu,%mem,cmd
deb http://security.ubuntu.com/ubuntu trusty-security multiverse
</pre>
deb-src http://security.ubuntu.com/ubuntu trusty-security multiverse
For example,
 
{{Pre}}
## Uncomment the following two lines to add software from Canonical's
$ ps -ef | grep akregator
## 'partner' repository.
brb      15013  1942  1 10:41 ?        00:00:05 akregator --icon akregator -caption Akregator
## This software is not part of Ubuntu, but is offered by Canonical and the
brb      15186 24045  0 10:50 pts/11  00:00:00 grep --color=auto akregator
## respective vendors as a service to Ubuntu users.
$ ps -p 15013 -o %cpu,%mem,cmd
# deb http://archive.canonical.com/ubuntu trusty partner
%CPU %MEM CMD
# deb-src http://archive.canonical.com/ubuntu trusty partner
1.0  0.8 akregator --icon akregator -caption Akregator
 
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu trusty main
deb-src http://extras.ubuntu.com/ubuntu trusty main
</pre>
</pre>
* http://askubuntu.com/questions/409607/how-to-create-a-customized-ubuntu-server-iso It gives a long instruction based on command line.
* http://razvangavril.com/linux-administration/custom-ubuntu-server-iso/ The instruction is organized and is very similar to the above.
* http://amjjawad.blogspot.com/2013/07/ubuntu-mini-iso-installation-process.html It does not talk about creating a customized iso. It talks about how to install Ubuntu from the minimal CD (~40M). The minimal CD will download the packages in the installation process.
==== Create your own Debian iso ====
* http://www.linuxuser.co.uk/tutorials/spin-your-own-debian


=== Selection of [http://en.wikipedia.org/wiki/Desktop_environment desktop environment] ===
'''pgrep'''
* https://wiki.archlinux.org/index.php/Desktop_environment
{{Pre}}
* http://www.pcworld.com/article/2951829/operating-systems/freedom-of-choice-7-top-linux-desktop-environments-compared.html
08:49AM ~$ ps -ef | grep firefox
* https://help.ubuntu.com/community/Installation/LowMemorySystems How to install desktops from the command line.
brb      7798  7778  0 08:49 pts/2    00:00:00 grep --color=auto firefox
* [http://askubuntu.com/questions/125062/how-can-i-find-which-desktop-enviroment-i-am-using To query the desktop environment] using the command line, use
brb      25486 24869  0 Sep10 ?        00:42:48 /usr/lib/firefox/firefox
<pre>
brb      25612 25486  0 Sep10 ?        00:19:49 /usr/lib/firefox/firefox .....
echo $DESKTOP_SESSION
08:49AM ~$ pgrep firefox
25486
</pre>
</pre>


On Ubuntu, it returns 'ubuntu' (gnome 3+unity), on Debian 8.0 it shows 'default' and on Debian's BBB, it returns 'LXDE' and on UDOObuntu 2 it shows 'Lubuntu'.
'''pidof'''
{{Pre}}
08:49AM ~$ pidof firefox
27951 25961 25612 25486
08:51AM ~$ pidof /usr/lib/firefox/firefox
27951 25961 25612 25486


==== [http://en.wikipedia.org/wiki/Unity_(user_interface) Unity] ====
$ kill $(pidof firefox)
Use 'unity --version' to check the unity version. If something was screwed up (eg after we remove gnome-desktop), we can reinstall the unity desktop by
<pre>
sudo apt-get install ubuntu-desktop
</pre>
</pre>


==== [http://en.wikipedia.org/wiki/GNOME GNOME] ====  
== Avoid concurrency ==
[http://ubuntugnome.org/ Ubuntu GNOME] (GNOME 3). The build-in screensaver is a digital clock showing the current time & date. Cool! This seems to be a new feature in GNOME 3.6 optimized for touch screen devices. See [https://help.gnome.org/misc/release-notes/3.6/users-lock-screen.html.en_GB this] and [http://www.linuxuser.co.uk/reviews/gnome-3-6-review-against-the-grain this].
[https://www.howtogeek.com/limit-bash-scripts-to-run-once-at-a-time/ Avoid These Problems By Limiting Bash Scripts to Run Once At A Time]. '''pgrep, lsof''' and '''flock''' commands.


[[File:UbuntuGnome1404.png|150px]] [[File:UbuntuGnome1404b.png|150px]]
== All You Need To Know About Processes in Linux ==
http://www.tecmint.com/linux-process-management/


Note that we can install the gnome desktop by using the command line. It will keep the current wallpaper. The clock in screensaver will not be shown until we shake the mouse or keyboard.
== wait command and background jobs ==
The '''wait''' command in Linux is a shell built-in command that pauses the execution of a shell script until all background jobs or specified JobID/PIDs terminate and return their exit status.
<pre>
<pre>
sudo apt-get install gnome-shell
# Example 1: Wait for all background processes to finish
# Choose 'gdm' (Gnome Desktop Manager) as the display manager instead of 'lightdm' the Ubuntu's default
command1 &
#    when it is configuring gdm as only GDM offers GNOME-specific features such as lock-screen notifications.
command2 &
# See the screenshot at
wait
#    https://ideasnet.wordpress.com/2013/05/11/ides-desktop-how-to-replace-unity-with-gnome-3-8-in-ubuntu-13-04-desktop-edition/
echo "All background processes have finished."
# If messed up, run "sudo dpkg-reconfigure gdm"
sudo apt-get install ubuntu-gnome-desktop
</pre>


If the lock screen does not work, use Settings > Brightness and Lock, or use the command line
# Example 2: Wait for a specific process to finish
<pre>
command1 &
gsettings set org.gnome.desktop.lockdown disable-lock-screen 'false'
PID=$!
command2 &
wait $PID
echo "Command1 has finished."
</pre>
</pre>


If the screensaver is not working, try
== run commands in a background and allow log off ==
<pre>
{{Pre}}
sudo apt-get install gnome-screensaver
nohup /path/to/script >output 2>&1 &
</pre>
</pre>
In my case, the screen turns off (black). But if we wake the PC up, the time and date screen shows up.


Some differences (inconvenience): 1. No maximize, minimize windows buttons 2. Have to click 'Activities' button (or 'Windows' key) to switch applications. These complains also appeared in other [http://www.linuxuser.co.uk/reviews/gnome-3-6-review-against-the-grain review].
Or to [http://stackoverflow.com/questions/10408816/how-do-i-use-the-nohup-command-without-getting-nohup-out disable output and be more safe]. It also explains the concept of '''file descriptor/fd''' in Unix.
{{Pre}}
nohup command </dev/null >/dev/null 2>&1 &
</pre>


==== [http://en.wikipedia.org/wiki/KDE KDE] ====
See also [https://en.wikipedia.org/wiki/Process_substitution#Anonymous_named_pipe Anonymous named pipe].
[http://www.kubuntu.org/ Kubuntu]


==== [http://en.wikipedia.org/wiki/Xfce Xfce] ====
See also [https://hide.me/en/vpnsetup/fedora/openvpn/ How to Setup OpenVPN on Fedora 24+] where we use '''nohup openvpn ... & ''' to start the connection in the background and also make it not terminate on exiting the terminal.
[http://xubuntu.org/ Xubuntu]. The response is quicker when I compare the speed by clicking the top-left icon (app menu) in Xfce and Acitvities button in ubuntu-GNOME. This is tested when both Xubuntu and ubuntu-GNOME are installed in VirtualBox.
<syntaxhighlight lang='bash'>
# Note the sources.list should contain 'universe' repositories.
# https://help.ubuntu.com/community/Repositories/Ubuntu
#
# Install XFCE alone, without Xubuntu, with this command:
sudo apt-get install xfce4
# Install the entire Xubuntu package, which includes a full suite of software and a lot of improvements:
sudo apt-get install xubuntu-desktop
#
# Note that installed terminal is XTerm and UXTerm which looks awful. We will want
# xfce4-terminal, a modern, lightweight and low memory cost terminal emulator for X11,
# which was included in the Xubuntu desktop.
sudo apt-get install xfce4-terminal
</syntaxhighlight>


The default display manager (used e.g. log in screen) can be found by
== job: How do I send an already-running process into the background ==
<syntaxhighlight lang='bash'>
* [https://www.makeuseof.com/run-linux-commands-in-background/ How to Run Linux Commands in the Background]
cat /etc/X11/default-display-manager
* http://stackoverflow.com/questions/625409/how-do-i-put-an-already-running-process-under-nohup
</syntaxhighlight>
* [https://www.cyberciti.biz/faq/unix-linux-bg-command-examples-usage-syntax/ bg Command Examples]
* [https://www.howtogeek.com/440848/how-to-run-and-control-background-processes-on-linux/ How to Run and Control Background Processes on Linux]
* [https://linuxhandbook.com/run-process-background/ Running Linux Commands in Background and Foreground]


To install lightdm display manager
Steps:
<syntaxhighlight lang='bash'>
# 'Ctrl+Z' to stop (pause) the program and get back to the shell. It [https://askubuntu.com/a/510816 sends SIGTSTP to a foreground application].
sudo apt-get install lightdm
# '''bg''' to run it in the background.
</syntaxhighlight>
# '''jobs -l''' to get the jobID and process ID
# '''disown -h [job-spec]''' where [job-spec] is the job number (like '''%1''' for the first running job; find about your number with the '''jobs''' command) so that the job isn't killed when the terminal closes.


After running the above command, I found 1. a GUI login screen came out, but login failed (my case). Use Ctrl+Alt+F1 to switch to the command line approach. 2. startx failed.
== Stopped job ==
A [https://unix.stackexchange.com/questions/116959/there-are-stopped-jobs-on-bash-exit stopped job] is one that has been temporarily put into the background and is no longer running, but is still using resources (i.e. system memory). Because that job is not attached to the current terminal, it cannot produce output and is not receiving input from the user.


==== [http://en.wikipedia.org/wiki/LXDE LXDE] ====
* '''jobs -s''' showing stopped jobs
[http://lubuntu.net/ Lubuntu], [http://lxle.net/ LXLE] and [http://lxqt.org/ LXQt]. LXDE is the default desktop environment for Raspbian, LXLE, BBB, and Lubuntu.
* '''jobs -l''' showing the job PID


The default browser in LXLE is SeaMonkey. In the Internet category, it also includes FireFTP (SeaMonkey extension), Transmission, Gitso (VNC), uGet. In the Sound/Video category, it includes Arista transcoder, Audacity, Guaydadeque Music Player, guncviewer, Pithos, RecordMyDesktop, Videos/Totem. Gedit, GParted, KeepassX and LibreOffice are standard. There is also a Games category.
[https://serverfault.com/questions/240155/how-can-i-kill-all-stopped-jobs Send kill to a stopped job, it will do nothing but queue than bring it in in foreground, it will terminate]. So don't repeatly sending a 'kill' command.
* '''fg %1''' move the stopped job ID #1 to the foreground (works)
* '''kill %1''' # kill job ID #1
* '''kill 12345''' # kill job PID 12345
* '''kill -9 `jobs -ps`''' may not work
* '''kill -9 $(jobs -p)'''


The [http://www.lxle.net/forums/discussion/972/lxle-ls-first-beta-available LXLE LS] version provides several business apps to anyone on the network.
== nice ==
[https://www.howtogeek.com/411979/how-to-set-process-priorities-with-the-nice-and-renice-commands-in-linux/ How to Set Process Priorities With nice and renice on Linux]


LXQt is the Qt port and the upcoming version of LXDE, the Lightweight Desktop Environment.
== watch command ==
[https://www.networkworld.com/article/3529891/watching-activity-on-linux-with-watch-and-tail-commands.html Watching activity on Linux with ''watch'' and ''tail'' commands]. Both the '''watch -n''' and '''tail -f''' commands can provide auto-updating views of information/


The download links (if we want to skip answering the question) are https://sourceforge.net/projects/lxle/files/Final/OS/.
We can use the '''watch''' command to monitor a specific process such as the progress of the ''dd'' command.


==== [http://en.wikipedia.org/wiki/Cinnamon_%28software%29 Cinnamon] ====
Terminal 1
[http://www.linuxmint.com/ Linux Mint]. A GTK+-based desktop environment. Note that [https://sites.google.com/site/easylinuxtipsproject/mint Mint releases only LTS versions] (5 years support as Ubuntu).
<pre>
watch -n 10 who
watch ps -C dd --format pid,cmd,%cpu
</pre>


Note this Cimmanon desktop has a digital clock as a screesaver while the MATE desktop only has a black screen as a screen saver.
Terminal 2
<pre>
dd if=/dev/zero of=/dev/null
</pre>


[[File:MintCinnamonSS.png|150px]]
Use '''--color''' for [https://stackoverflow.com/a/3794222 color output].


==== [http://en.wikipedia.org/wiki/MATE_(software) MATE] ====
== while + sleep ==
[https://ubuntu-mate.org/ Ubuntu Mate]. The MATE Desktop Environment is the continuation of GNOME 2.
[https://www.linuxuprising.com/2020/12/how-to-repeat-command-every-x-seconds.html How To Repeat A Command Every X Seconds On Linux]: watch, while + sleep,


==== Pantheon ====
== ulimit ==
[https://elementary.io/ Elementary OS]. I cannot make the Chinese input to work (I can install ibus-chewing but cannot switch input methods?).
* [https://www.cyberciti.biz/faq/how-to-find-ulimit-for-user-on-linux/ How to find ulimit for user on Linux]
* [https://www.cloudsavvyit.com/10159/setup-a-completely-unlimited-limits-conf-configuration-for-testing-servers/ Setup a Completely Unlimited limits.conf Configuration for Testing Servers]


=== gparted on a 4TB disk ===
= Notepadqq - Notepad++-like editor =
Get an error when I tried to create partitions on a 4T disk. Search 4TB gparted sectors exceeds the msdos-partition-table-imposed maximum of 4294967295
[http://www.ubuntugeek.com/notepadqq-the-linux-source-editor.html Notepadqq]. It is written using Qt. It does not have printing function:(


It seems it is necessary to use '''GPT''' instead of '''MBR/msdos''' as a partition table to overcome 2TB limitions.
= Note apps that can sync =
[http://www.makeuseof.com/tag/top-notepad-apps-linux-can-sync/ Top 8 Notepad Apps for Linux That You Can Sync]. Some are compatible with Evernote.


It is also a good idea to use a live gparted os since the one in Ubuntu may not be up-to-date and gparted takes forever to scan devices. When boot from live USB, we need to turn off the Ext hard disk first.
= Evernote =
== Evernote alternative ==
[https://www.howtoforge.com/tutorial/how-to-install-turtl-server-evernote-alternative-on-ubuntu-1604/ How to Install Turtl Server - Evernote Alternative - on Ubuntu 16.04]


Step1. Device -> Create a partition table -> GPT
== Backup/restore Evernote ==
https://www.makeuseof.com/tag/backup-restore-evernote/


Step2. Create a new ext4 partition as you want.
= Markdown =
== Preview markdown/view markdown offline ==
* [https://atom.io/ Atom] text editor has a built-in function to preview HTML or markdown files. Menu -> Packages -> Markdown Preview -> Toggle Preview.
* http://stackoverflow.com/questions/9843609/view-markdown-files-offline. [https://github.com/joeyespo/grip Grip] works fine. 
{{Pre}}
sudo pip install grip
grip readme.md
</pre>
* For image, see http://stackoverflow.com/questions/13051428/how-to-display-images-in-markdown-files-of-github. The trick is adding '''?raw=true''' after the image name.
<pre>
# title 1
![screenshot](myfile.png?raw=true)
</pre>
* Chrome ''markdown preview plus'' extension does not show images from github.


* http://ubuntuforums.org/showthread.php?t=2164361
== Markdown editor ==
* http://gparted-forum.surf4.info/viewtopic.php?id=14940
* [http://pad.haroopress.com/ Harropad]
* http://askubuntu.com/questions/339041/cannot-resize-drive
* http://linuxbsdos.com/2014/10/05/the-best-markdown-editors-for-linux/
* http://unix.stackexchange.com/questions/67835/change-partition-table-with-gparted


Note:
= Text editor with navigation =
* The 4TB hard disk can be recognized and used normally in an internal hd in Ubuntu 12.04.
[[Text_editor#Text_editor_with_navigation|Text editor with navigation]]
* The 4TB hard disk can also be used in Windows 7 as an external hd if I formatted it (e.g. from gparted in Linux) as an NTFS partition. The Disk Management (command prompt -> diskmgnt.msc) shows it has 3726.02 GB (3726.02 * 1024 * 1024 * 1024 = 4.000784e12 Bytes) capacity and the windows manager shows it is 3.63TB (3726.02/1024=3.638) total space.
* It cannot be used as 4TB in the case when I use a docking station in Dell Precision T3500. Unsolved problem:
** Running the command chown from root to user takes forever on 4T partition.
** The ext dock station (StarTech) will halt the shutdown until I power off the station?


Conclusion:
= nano/pico editor =
* 4TB using NTFS works on Ubuntu.
The nano editor is also called pico in R. See ?edit in R.
* rsync will not stop spinning for some reason even the command is finished.


=== tracker-miner-fs ===
[[Text_editor#nano_editor|nano editor]]
See http://askubuntu.com/questions/346211/tracker-store-and-tracker-miner-fs-eating-up-my-cpu-on-every-startup how to disable it.


=== Health check of the hdd ===
= vi editor =
I got an input/output error when I use ''sudo rm'', ''sudo reboot'' or ''Ctrl + Del'' commands.
[[Text_editor#vi_editor|vi editor]]


When I use the power button to force shutdown, I could not boot again. The BIOS does find the hdd and the Ubuntu Live USB does find the internal hdd too.
= Cloud =
[[Cloud|Cloud]]


To force to reboot/shutdown, follow the suggestion [http://linoxide.com/how-tos/inputoutput-error-bad-blocks-how-to-restart-linux/ here]
= Boot =
* [https://opensource.com/article/18/1/analyzing-linux-boot-process Analyzing the Linux boot process]
* [https://utcc.utoronto.ca/~cks/space/blog/linux/LinuxBootOverview? A broad overview of how modern Linux systems boot]


'''dmesg''' command shows there are a few bad sectors on that hdd.  
== U-boot ==
http://www.denx.de/wiki/U-Boot


http://www.howtogeek.com/howto/37659/the-beginners-guide-to-linux-disk-utilities/ shows a few ways to run a health check on the hdd. The gnome disk utility cannot run S.M.A.R.T. on the external hdd.
= Pandora linux client =
<pre>
* [http://kevinmehall.net/p/pithos/ Pithos] (GUI)
sudo badblocks -v /dev/sdb1
* [http://6xq.net/projects/pianobar/ Pianobar] (Command line)
sudo badblocks /dev/sdb > /home/zainul/bad-blocks
sudo fsck -l bad-blocks /dev/sdb
</pre>


This article http://linoxide.com/linux-how-to/how-to-fix-repair-bad-blocks-in-linux/ talks about how to fix/repair bad blocks in Linux
= COW (copy on write) file system =
.
[[Filesystem|filesystem]]


This article http://unix.stackexchange.com/questions/25902/what-does-this-hard-disk-error-message-mean-current-pending-sector-count talks about how to do with bad sectors.
= tmpfs and /dev/shm =
* [https://www.howtoforge.com/storing-files-directories-in-memory-with-tmpfs Storing Files/Directories In Memory With tmpfs]
* [https://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html What Is /dev/shm And Its Practical Usage]
* [https://lonesysadmin.net/2013/12/14/use-ram-disk-improve-disk-access-times/ Use a RAM Disk to Improve Disk Access Times]
* [https://kerneltalks.com/linux/how-to-create-ram-disk-in-linux/ How to create RAM disk in Linux]
* [https://www.cloudsavvyit.com/10362/how-to-enlarge-tmpfs-space-in-linux/ How to Enlarge tmpfs Space in Linux], [https://www.cloudsavvyit.com/10254/how-to-create-a-ram-drive-in-linux/ RAM Drive vs tmpfs instance]


It is an indicator that hdd is going to die http://www.linuxquestions.org/questions/linux-hardware-18/34-bad-blocks-what-should-i-do-927224-print/.
= Apache redirection =
http://cran.r-project.org/mirror-howto.html


=== Write an iso or img file to a USB flash drive ===
[http://www.tecmint.com/redirect-website-url-from-one-server-to-different-server/ Redirect a Website URL from One Server to Different Server in Apache]
[http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows Official instruction] on www.ubuntu.com
* If your current OS is windows => [http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/#button Universal USB Installer/Live Linux USB Creator].
* If your current OS is Ubuntu => [https://help.ubuntu.com/community/Installation/FromUSBStick#Creating_a_bootable_Ubuntu_USB_flash_drive_from_Ubuntu Several choices] like '''Startup Disk Creator''' ([[has an option on the GUI to erase the usb drive]])/usb-creator or UNETBOOTIN (no option to erase the USB so it can fail) or mkusb. But in LXLE 14.04.3 Startup Disk Creator is dropped for '''[http://multibootusb.org/ MultiBootUSB]''' for more features and flexibility.
* If your current OS is Mint => Right click the iso file and select Make bootable USB stick. No software to install.


==== Use dd ====
= Important linux directories =
First, get to know the USB drive device name like /dev/sdb. When using 'dd', the USB drive has to be unmounted (using 'umount' command, not click 'reject' button in File Manager). Note that this will irrevocably destroy all data on /dev/sdX.
[https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html Filesystem Hierarchy Standard], [https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard Wikipedia]


The instruction can be found in a lot of places like [https://wiki.archlinux.org/index.php/USB_Flash_Installation_Media Archlinux wiki] page.
* /bin - executables used by the base system
<syntaxhighlight lang='bash'>
* /boot
sudo fdisk -l
* /dev
sudo dd bs=4M if=xxx.img of=/dev/sdb && sync
* '''/etc''' - configuration files
</syntaxhighlight>
* /media
where /dev/sdb is a device name, not a partition name. We can also adjust bs to a smaller value like 1M, 4m.
* /mnt
 
* /opt - optional application packages
To monitor the progress, see [[Raspberry#Install_an_image_to_a_SD_card|Raspberry Pi]] page.
* /proc - process information only. [https://levelup.gitconnected.com/access-kubernetes-objects-data-from-proc-directory-8d2ec6a0faba Access Kubernetes Objects Data From /Proc Directory]
<syntaxhighlight lang='bash'>
* /sbin - critical executables for running the system, but should be used by superuser
sudo pkill -USR1 -n -x dd
* '''/usr''' - user programs and data. For example /usr/bin contains most of the libraries used by apps. [https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s11.html /usr/share/] contains Architecture-independent data (eg some pretty images are located in /usr/share/backgrounds)
</syntaxhighlight>
* '''/var''' - variable data such as '''databases''', mails spools and system '''logs'''.


For some reason when I use dd to create ubuntu 14.04 on usb drive, sudo gparted also gives me a Libparted warning ''/dev/sdc contains GPT signature, indicating that it has a GPT table. However, it does not have a valid fake msdos partition table, as it should... Is it a GPT partition table?'' messsage. If I click 'Yes', Gparted shows no partition on the usb drive??? Nevertheless, the usb drive can be used to boot into ubuntu 14.04.
= Difference of /bin, /sbin, /usr/local/bin, ... =
* '''/bin''' : For essential binaries; e.g. bash, cat, ls.
* '''/sbin''' : is similar to /bin but for scripts with superuser (root) privileges required; e.g. shutdown command is located here. Local users have to use sudo to run binaries here.
* '''/usr/bin''' : Same as first, but for general system-wide & non-essential binaries; e.g. grep, zip, docker, etc.
* '''/usr/sbin''' : Same as above, but for scripts with superuser (root) privileges required.
* '''/usr/local/bin''' or '''/usr/local/sbin''' for system-wide available (personal) scripts. For example, install [https://docs.docker.com/compose/install/ docker-compose] is merely to download the binary and place it under /usr/local/bin/ directory.


In another case, the gparted compalins the usb drive "Invalid partition table - recursive partition on /dev/sdb". Someone suggests to issue a command
If you want to create your own scripts and make them available to all users, you’re pretty safe adding them to '''/usr/local/bin'''. Or to add my scripts to my local bin (~/bin) and then I create a symbolic link in /usr/local/bin to the commands I want to make public. As a result, I can manage all my scripts from the same directory but still make some of them publicly available since /usr/local/bin is added to $PATH. See [http://blog.taylormcgann.com/2014/04/11/difference-bin-sbin/ this post].
<syntaxhighlight lang='bash'>
sudo dd if=/dev/zero of=/dev/sdb bs=4M
</syntaxhighlight>


==== UNETBOOTIN ====
= DHCP =
The GUI is written by Qt so the program is cross-platform. See its [http://sourceforge.net/p/unetbootin/wiki/compile/ wiki].


http://xubuntugeek.blogspot.com/2013/04/how-to-install-xubuntu-on-usb-device.html
== DHCP server IP ==
<syntaxhighlight lang='bash'>
[https://www.cyberciti.biz/faq/linux-find-out-dhcp-server-ip-address/ Linux find DHCP server IP address using CLI]
sudo apt-get install unetbootin extlinux -y
</syntaxhighlight>


The following is a screenshot of the contents of xubuntu 12.04. '''The usb drive needs to be formatted to fat32''' on Windows OS to repair partition table error. The partition table error was discovered when I use sudo gparted program to view the USB drive.
== Get a New IP Address ==
{{Pre}}
dhclient -r  #  release your IP Address


Note that Unetbootin (Windows & Linux) and Universal USB installer (Windows only) are quite similar although Universal USB installer provides more options in its interface while Unetbootin does not have any other options.
dhclient  #  get your DHCP to issue you a new IP Address based on how it’s been configured.
</pre>


[[File:XUbuntu12044 USBdrive.png|200px]]
= Open a file/URL using the default application from the command line =
[[File:XUbuntu gparted.png|200px]]
* '''gnome-open''' (works on Mint)
* '''kde-open''' (KDE users)
* '''xdg-open''' (window-manager independent). XDG stands for X Desktop Group; see https://en.wikipedia.org/wiki/Freedesktop.org


=== [http://www.pendrivelinux.com/yumi-multiboot-usb-creator/ YUMI] ===
See also
YUMI works much like Universal USB Installer, except it can be used to install more than one distribution to run Live from your USB.
* [https://unix.stackexchange.com/questions/149033/how-does-linux-choose-which-application-to-open-a-file How does Linux choose which application to open a file?]
* [https://www.howtogeek.com/117709/how-to-change-your-default-applications-on-ubuntu-4-ways/ How to Change Your Default Applications on Ubuntu: 4 Ways]


It can be used to create a Multiboot USB Flash Drive containing multiple operating systems, antivirus utilities, disc cloning, diagnostic tools, and more.
= Check a file's encoding =
{{Pre}}
file -bi myfile
</pre>
For example,
{{Pre}}
file -bi Downloads/hmv_.rc
# text/x-c++; charset=utf-16le
</pre>


==== Universal USB Installer/UUI ====
= Know you system using the command line =
http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/
* https://www.howtoforge.com/tutorial/get-to-know-your-system/


I first used ''dd'' command to successfully created a xubuntu 14.04 usb drive but there seems to be a problem with the partition since the gparted program will give a warning message about that and also the whole 16GB was used when I insert the drive onto a Windows machine.
= Alerting and visualization tools =
[https://opensource.com/article/18/10/alerting-and-visualization-tools-sysadmins 5 alerting and visualization tools for sysadmins]


Note that the '''fdisk''' utility cannot handle this new partition format so we have to use the '''gparted''' program.
= System monitor tools (TUI) =


Open the '''gparted''' program. Use it MULTIPLE TIMES to create a partition table (Device -> Create Partition Table...). Then we create a FAT32 partition with all of the space. After that, we can use the UUI program to create an Ubuntu USB drive.
== glances command: more than htop ==
* https://nicolargo.github.io/glances/ and its [http://glances.readthedocs.io/en/latest/ Documentation]. It seems to be more stable to install via apt command instead of the bash script. There is no need to use 'sudo' to run the command.
* [http://www.ubuntugeek.com/install-glances-on-ubuntu-16-04.html Glances] includes Disk I/O, Network I/O, internal and '''external''' IPs, current time, et al. Its official website at http://glances.readthedocs.io/en/latest/.
** Glances uses online services to grab the external IP address. https://github.com/nicolargo/glances/issues/961
** To hide the internal and external IPs, type "I" (capital).
** To disable the IP, type "--disable-ip" (not available in v3.x.x ?)
** It shows a warning or critical alert (e.g. memory high usage) at the bottom of the screen.
** My command: '''glances -t 5'''  # update every 5 seconds
* https://www.tecmint.com/glances-an-advanced-real-time-system-monitoring-tool-for-linux/
* [https://youtu.be/E3Ioopzt8ko Monitoring & Troubleshooting Basics with Glances] (video)


The following screenshots are from a 16GB USB drive.
Glances is similar to htop but it provides network stats and disk usage too. It also supports web UI. Install it by '''sudo apt-get install glances'''.


[[File:UUIa.png|200px]] [[File:UUIb.png|200px]]
== [https://github.com/brndnmtthws/conky conky] and autostart ==
* [[Ubuntu#Conky|Ubuntu > Conky]] (internal link)
* [[Raspberry#Conky_approach|Raspberry Pi]] case (internal link)


=== Determine/install/switch Window Manager ===
For auto start on Lubuntu, see [https://askubuntu.com/a/1148628 How can I add new autostart programs in Lubuntu?]
* http://askubuntu.com/questions/72549/how-to-determine-which-window-manager-is-running
* http://askubuntu.com/questions/227607/different-display-and-window-managers-for-ubuntu-and-how-to-install-them


<pre>
On Lubuntu 18.04, add the path to the application to ~/.config/lxsession/Lubuntu/autostart
sudo apt-get install wmctrl
wmctrl -m         


sudo apt-get install <pkg-name>
== '''top''' and '''htop''' command ==
<pkg-name> --replace
* [https://www.binarytides.com/linux-top-command/ 15 simple TOP command examples on Linux to monitor processes]
</pre>
** M (capital): sorted by memory
** P: sorted by CPU
** T: sorted by running time
** c: full command path
** u: filter by user
** V: forest/tree mode; parent child hierarchy. This will disable 'M', 'P' or 'T'.
** f: show/hide columns
** '''top -d 5''' change the refresh interval from 3 seconds to 5 seconds
* [https://askubuntu.com/a/613645 Why are some processes highlighted in top?]
* Htop command has a screen help. [https://www.softprayog.in/tutorials/htop-command-in-linux htop command in Linux]
** Tree view. Press 't'. Press '+' or '-' to expand or collapse.
** ">" to change to sort view.
* [https://www.thegeekstuff.com/2011/09/linux-htop-examples/ Shortcut character keys and function keys]
* [http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages Understand Linux CPU Load]. The maximum number should be the number of cores.
* In Armbian, htop shows CPU temperature and frequencies; see a [https://forum.armbian.com/topic/10295-updated-htop/?tab=comments screenshot].


On Ubuntu the default window manager is '''Compiz''', for xubuntu it is '''Xfwm4''' and for BBB it is '''Openbox'''.
== nmon ==
* https://en.wikipedia.org/wiki/Nmon. The stats are saved to a comma-separated values (CSV) data file for later graphing and analysis
* [https://nmon.sourceforge.io/pmwiki.php HomePage]
* [https://www.admin-magazine.com/HPC/Articles/Nmon-All-Purpose-Admin-Tool Monitoring with Nmon]


=== Add date and time to the clock indicator on the top panel ===
== CPU frequency ==
Method 1. GUI approach. Right click the clock indicator and choose Time and Date Settings. Click on 'clock' tab and check 'date and month' option.
[https://ostechnix.com/optimize-performance-and-battery-life-with-auto-cpufreq/ How To Optimize Performance And Battery Life With Auto-cpufreq In Linux]


Method 2. [https://www.liberiangeek.net/2012/05/show-the-date-and-time-on-the-clock-indicator-in-ubuntu-12-04-precise-pangolin/ Command line approach].
[https://unix.stackexchange.com/a/265611 What is the correct way to view your CPU speed on Linux?] (x86)
<pre>
<pre>
gsettings set com.canonical.indicator.datetime show-date true
watch -n.1 "cat /proc/cpuinfo | grep \"^[c]pu MHz\""
</pre>
</pre>


=== Automatic update ===
[https://unix.stackexchange.com/a/590531 How can I get the current CPU frequency of an ARM processor on Ubuntu?]
http://www.howtogeek.com/228690/how-to-enable-automatic-system-updates-in-ubuntu/
 
=== After running update/upgrade in Ubuntu ===
Virtualbox does not work. After initial fix, the guest machine cannot connect to internet:(
 
=== Install/upgrade graphics driver ===
* http://www.ubuntugeek.com/install-updated-and-optimized-open-graphics-drivers-radeon-intel-and-nvidia-on-ubuntu-15-0414-04.html
* http://www.howtogeek.com/242045/how-to-get-the-latest-nvidia-amd-or-intel-graphics-drivers-on-ubuntu/
 
=== System program problem detected ===
* http://askubuntu.com/questions/365358/im-getting-a-lot-of-system-program-problem-detected-error-dialogs-is-there-a
<pre>
<pre>
sudo rm /var/crash/*
ls /sys/devices/system/cpu/cpu0/cpufreq/
</pre>
</pre>
* http://www.techdrivein.com/2012/08/how-to-disable-system-program-problem.html. sudo nano /etc/default/apport.
Change value of "enabled" from 1 to 0. Then reboot.


=== Autostart ===
== [https://scoutapp.github.io/scout_realtime/ scout_realtimep] ==
http://www.howtogeek.com/228467/how-to-make-a-program-run-at-startup-on-any-computer/
This is used by [https://docs.dataplicity.com/docs/remotely-monitor-your-pi Dataplicity]


Look at the hidden directory  ~/.config/autostart/. Add .desktop files to here to have programs start automatically at startup. These .desktop files are application shortcuts — you can often create them by dragging-and-dropping an application onto your desktop or even just into the ~/.config/autostart/ window.
== [https://github.com/aksakalli/gtop gtop] command (100% Javascript) ==
https://www.cyberciti.biz/howto/gtop-awesome-system-monitoring-dashboard-for-terminal/.  


If you’re not using a desktop environment check out '''~/.bash_profile''' file.
Pros:
* CPU history graph in time
* Memory history graph in time (not useful)
* Network bandwidth usage is real-time. It is accurate as what [[#nload|nload]] gives.
* Percentage usage of memory, swap, disk usage
* Top processes


=== Conky ===
{{Pre}}
[http://conky.sourceforge.net/ Conky] is a free, light-weight system monitor for X, that displays any information on your desktop.
$ docker run --rm -it \
    --name gtop \
    --net="host" \
    --pid="host" \
    aksakalli/gtop


* https://help.ubuntu.com/community/SettingUpConky
$ sudo apt install npm nodejs
* https://github.com/zenzire/conkyrc (this one works). Check [http://woeid.rosselliot.co.nz/ for the WOEID] for your city used in the [http://www.yahooapis.com/weather/ Yahoo weather API].
$ npm install gtop -g
* http://www.ifxgroup.net/conky.htm
$ gtop
* http://www.tomshardware.com/faq/id-1882395/write-conky-config-file.html Explain conkyrc file
</pre>


Step 1. Install conky-all package
* Press p to sort by process ID (PID).
* Press c to sort by CPU usage.
* Press m to sort by memory usage.


Step 2. create ~/.conkyrc file. This file can be downloaded from web.
It can be installed on Linux Mint 18.2 but not in Ubuntu 14.04 or raspbian (9 stretch).  
<pre>
$ npm install gtop -g
npm http GET https://registry.npmjs.org/gtop
npm http GET https://registry.npmjs.org/gtop


Step 3. Run it: $ conky. If we want to run a specific configuration file, use conky -c CONKYRCFILE
npm http GET https://registry.npmjs.org/gtop
npm ERR! Error: CERT_UNTRUSTED
npm ERR!    at SecurePair.<anonymous> (tls.js:1370:32)
npm ERR!    at SecurePair.EventEmitter.emit (events.js:92:17)
npm ERR!    at SecurePair.maybeInitFinished (tls.js:982:10)
npm ERR!    at CleartextStream.read [as _read] (tls.js:469:13)
npm ERR!    at CleartextStream.Readable.read (_stream_readable.js:320:10)
npm ERR!    at EncryptedStream.write [as _write] (tls.js:366:25)
npm ERR!    at doWrite (_stream_writable.js:223:10)
npm ERR!    at writeOrBuffer (_stream_writable.js:213:5)
npm ERR!    at EncryptedStream.Writable.write (_stream_writable.js:180:11)
npm ERR!    at write (_stream_readable.js:583:24)
npm ERR! If you need help, you may report this log at:
npm ERR!    <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!    <npm-@googlegroups.com>


Step 4. If you want to stop Conky: $ killall conky
npm ERR! System Linux 4.4.0-119-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "gtop" "-g"
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.10
</pre>


Note that conky works automatically on Ubuntu's Unity.  
== [https://github.com/cjbassi/gotop gotop] ==
A terminal based graphical activity monitor inspired by gtop and vtop. It is quite beautiful.


For Lubuntu (tested on 14.04), the Conky's transparent function does not work at first. But [http://gnome-look.org/content/download.php?content=170851&id=1&tan=63968661 This conkyrc] works on Lubuntu desktop (mainly, tranparent function). To deal with the autostart, follow the suggestion from [http://askubuntu.com/questions/81383/how-can-i-add-new-autostart-programs-in-lubuntu askubuntu.com]. That is, go to ~/.config/autostart folder, create or copy+paste the file called '''conky.desktop''' with a content like
[https://www.ostechnix.com/gotop-yet-another-tui-graphical-activity-monitor-written-in-go/ Gotop – Yet Another TUI Graphical Activity Monitor, Written In Go]
<pre>
[Desktop Entry]
Type=Application
Exec=sh "/home/brb/.conky/conky-startup.sh"
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_IN]=Conky
Name=Conky
Comment[en_IN]=
Comment=
</pre>
and
<pre>
brb@brb-VirtualBox:~$ cat .conky/conky-startup.sh
conky &
exit 0
brb@brb-VirtualBox:~$ ls -l .conky/conky-startup.sh
-rw-rw-r-- 1 brb brb 37 Aug 30 20:17 .conky/conky-startup.sh
</pre>


Another way to configure conky is to install conky-manager. See [http://www.itworld.com/article/2696428/install-conky-manager-2-1-in-ubuntu-14-04.html this] and [http://www.teejeetech.in/p/conky-manager.html project website] page. But it seems it does not work well with desktop wallpaper.
Compared to gtop, it has a temperature monitor. However, it can only show the average CPU usage (one line) on my Xeon computer.


=== What should I do when Ubuntu freezes? ===
{{Pre}}
* http://askubuntu.com/questions/4408/what-should-i-do-when-ubuntu-freezes
git clone --depth 1 https://github.com/cjbassi/gotop /tmp/gotop
* https://en.wikipedia.org/wiki/Magic_SysRq_key
/tmp/gotop/scripts/download.sh
sudo cp gotop /usr/local/bin; rm gotop
gotop
</pre>
Note the temperatures do not show up in Raspbian (raspberry pi 3 b+).


Press Alt+Print and then type 'REISUB' (not work, it only does screenshot)
=== termui: Golang terminal dashboard ===
https://github.com/gizak/termui


=== [https://help.ubuntu.com/community/Repositories/Ubuntu Ubuntu Software Repository] ===
=== Bashtop and btop ===
The repository components are:
* [https://www.linuxuprising.com/2020/04/bashtop-is-cool-linux-resource-monitor.html Bashtop Is A Cool Linux Resource Monitor Written In Bash]
* [https://github.com/aristocratos/btop *btop]. C++ version and continuation of bashtop and bpytop. This is very similar to bashtop but it also shows the IP. Mac, Linux x86, armv7, aarch64, arm64, armv5. [https://lindevs.com/install-btop-on-raspberry-pi/ Install btop++ on Raspberry Pi], [https://lindevs.com/install-btop-on-ubuntu/ Ubuntu 22.04].


# Main - Officially supported software.
== S-tui command ==
# Restricted - Supported software that is not available under a completely free license.
[https://www.cyberciti.biz/python-tutorials/monitor-linux-cpu-temperature-frequency-power-in-a-graphical-way/ Monitor Linux CPU temperature, frequency, power in a graphical way]
# Universe - Community maintained software, i.e. not officially supported but enabled by default software.
# Multiverse - Software that is not free.


See the pitfall in the [http://www.pcworld.com/article/2845072/ubuntu-owncloud-and-a-hidden-dark-side-of-linux-software-repositories.html PCWorld] article.
== below ==
[https://fedoramagazine.org/below-a-time-traveling-resource-monitor/ below: a time traveling resource monitor]


=== "Failed to download Package Files" - Software Updater ===
= System monitor tools (GUI) =
[http://ubuntuforums.org/showthread.php?t=2196376 One solution] is to run the following command first
<pre>
sudo apt-get update && sudo apt-get upgrade
</pre>
and then run the software updater. Usually it requires the computer to restart.


I personally adjust the frequency of notification by choosing 'Every two weeks' for Automatically check for updates, etc.
Comparisons:
* https://www.tecmint.com/category/monitoring-tools/
* https://www.tecmint.com/linux-performance-monitoring-tools/
* https://linoxide.com/monitoring-2/linux-performance-monitoring-tools/
* http://www.linuxscrew.com/2012/03/22/linux-monitoring-tools/
* https://www.infoworld.com/article/2683857/network-monitoring/article.html#slide2
* http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools


=== apt-get upgrade vs apt-get dist-upgrade ===
Some lists:
* http://askubuntu.com/questions/194651/why-use-apt-get-upgrade-instead-of-apt-get-dist-upgrade
* [http://www.ubuntugeek.com/install-ganglia-on-ubuntu-16-04-server-xenial-xerus.html Install Ganglia on Ubuntu 16.04 Server (Xenial Xerus)]
* [http://www.ubuntugeek.com/install-linux-dash-web-based-monitoring-tool-on-ubntu-15-04-server.html Linux Dash] Web based monitoring tool. Source code is on [https://github.com/afaqurk/linux-dash github].
* [http://www.monitorix.org/ Monitorix] and on [https://www.howtoforge.com/tutorial/performance-monitoring-with-monitorix-on-ubuntu-16-04/ Ubuntu16.04]


My experience aligns with the statement: '''dist-upgrade''' is more likely to break stuff badly than '''upgrade'''.
== Linux-Dash ==
https://github.com/afaqurk/linux-dash. Not working when I tested on RPi and Ubuntu.


=== Customize the desktop ===
== Nagios ==
* Install Cairo-Dock.
* [http://www.nagios.org Nagios], [http://www.ubuntugeek.com/install-nagios-core-4-1-1-on-ubuntu-16-04-xenial-xerus-server.html Install Nagios core 4.1.1 on Ubuntu 16.04 (Xenial Xerus) Server]
* [https://en.wikipedia.org/wiki/Icinga Icinga] (Nagios fork)
** [http://www.ubuntugeek.com/how-to-install-icinga-nagios-fork-in-ubuntu-12-10-server.html icinga]
** [https://www.howtoforge.com/tutorial/how-to-install-icinga2-on-debian-9/ How to Install Icinga 2 Monitoring Tool on Debian 9.2]
** [https://www.howtoforge.com/tutorial/add-a-new-host-and-service-to-be-monitored-by-icinga2/ Add a new Host and Services to be Monitored by Icinga 2]


==== Remove overlay scroll bar ====
== [https://www.zabbix.com/ Zabbix] ==
http://www.itworld.com/article/2698420/disable-overlay-scroll-bars-in-ubuntu-14-04.html
* [https://www.tecmint.com/install-zabbix-on-debian-10/ How to Install Zabbix on Debian 10]
* [https://forum.proxmox.com/threads/smart-error-health-detected-on-host.109580/ SMART error (Health) detected on host]
* [https://www.zabbix.com/integrations/smart Zabbix + S.M.A.R.T.]


==== change scroll bar color ====
== Munin and Monit ==
See [http://ubuntuforums.org/showthread.php?t=1172617 this post]. Run sudo apt-get install gnome-color-chooser.  
[https://www.howtoforge.com/tutorial/server-monitoring-with-munin-and-monit-on-ubuntu-16-04-lts/ Server Monitoring with Munin and Monit] on Ubuntu 16.04 LTS


Go to Engines tab in gnome-color-chooser and choose clearlooks engine for scrollbars.
== [https://www.cacti.net/ Cacti] ==
* http://terraltech.com/monitoring-with-cacti/
* https://www.howtoforge.com/tutorial/install-cacti-on-debian-9/


=== [http://www.gnu.org/software/grub/ Grub2] ===
== [https://github.com/sysstat/sysstat sysstat], sar ==  
To show the grub2 screen, run 'sudo nano /etc/default/grub' and comment out the line GRUB_HIDDEN_TIMEOUT=0 and change the line GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" to GRUB_CMDLINE_LINUX_DEFAULT="". Remember to run 'sudo update-grub' after any change to grub.
{{Pre}}
# CPU
sar 2 10 # every two seconds, 10 times
# Memory
sar -r  # look at the kbcommit and commit columns


To add a splash image, follow the instruction at https://help.ubuntu.com/community/Grub2/Displays. Note that Grub2 will search the image based on some priority and there are also some minor requirements on the images. To test
sar -r -f /var/log/sysstat/sa02
<pre>
sudo apt-get install grub2-splashimages
sudo cp /usr/share/images/grub/Moraine_Lake_17092005.tga /boot/grub/
sudo update-grub
</pre>
</pre>
* https://www.maketecheasier.com/monitor-linux-performance-with-sysstat/
* https://www.tecmint.com/install-sysstat-in-linux/
* http://www.thegeekstuff.com/2011/03/sar-examples/
* https://www.blackmoreops.com/2014/06/18/sysstat-sar-examples-usage/
* [https://www.linux.com/news/visualize-sar-data-ksar Visualize sar data with kSar].
*# '''export LC_ALL=C'''.  This will convert date/time. For example, 12:00:01 AM will become 00:00:01 and 12/09/2017 will become 12/09/17.
*# '''sar -A -f /var/log/sysstat/saXX > ~/Downloads/sardata.txt'''.
*# Click on Data -> Load from text file. Select ~/Downloads/sardata.txt file. ''Note that nothing will happen in the kSar GUI''.
*# Click 'kSar' to show the tree.
* [https://www.cyberciti.biz/tips/identifying-linux-bottlenecks-sar-graphs-with-ksar.html kSar] (depends on JDK) for graphics (instead of usinsg the '''sadf''' command).
*# Download and unzip it to ~/bin.
*# Execute '''bash ~/bin/kSar-5.0.6/run.sh'''.
*# On the GUI, click Data -> Run local command.. -> '''sar 2 10''', for example. This will start to record the cpu usage 10 times with a 2 seconds interval.
*# You can view the real-time plot (shown on the right panel) by clicking kSar -> CPU -> CPU all (left panel).


* [https://www.howtoforge.com/tutorial/repair-grub-2-ubuntu/ Repair Grub2]
== Stacer ==
[[Ubuntu#Stacer_-_Linux_System_Optimizer_and_Monitoring|Linux System Optimizer and Monitoring]]


=== Boot from an NFS server ===
== Prometheus ==
* http://www.linuxuser.co.uk/tutorials/boot-linux-from-an-nfs-server
* https://prometheus.io/docs/introduction/overview/
* [https://www.howtoforge.com/how-to-install-prometheus-system-monitoring-tool-on-debian-11/ How to Install Prometheus System Monitoring Tool on Debian 11]


With NFS booting, the core kernel and file systems are kept on a central server and then pushed out onto client systems to be booted on there. That means your files and desktop will always be available wherever you want to log in.
= [https://en.wikipedia.org/wiki/Curses_%28programming_library%29 Curses] and [https://en.wikipedia.org/wiki/Ncurses ncurses]: TUI library =


At the end, the client computer does not need any internal storage. Cool!
[https://opensource.com/article/21/8/ncurses-linux Position text on your screen in Linux with ncurses]


=== [https://help.ubuntu.com/lts/serverguide/network-file-system.html Network File System (NFS)] ===
== Calcurse ==
NFS allows a system to share directories and files with others over a network. By using NFS, users and programs can access files on remote systems almost as if they were local files.
[https://opensource.com/article/18/10/calcurse Keep up with your calendar and to-do list with Calcurse]


Some of the most notable benefits that NFS can provide are:
= Bitbucket (free for 5 users) =
* Local workstations use less disk space.
[https://confluence.atlassian.com/display/BITBUCKET/Bitbucket+101  Bitbucket 101]
* There is no need for users to have separate home directories on every network machine. Home directories could be set up on the NFS server and made available throughout the network.


'''Server part''':
* Unlimited private repos
<syntaxhighlight lang='bash'>
* Code reviews
sudo apt-get install nfs-kernel-server
* JIRA integration
</syntaxhighlight>
* REST API
* Custom domains


Configure the directories to be exported by adding them to the '''/etc/exports''' file.
See this [https://answers.atlassian.com/questions/148713/sourcetree-commit-author-change-update post] to know how to fix the problem of unknown author. In short, when I uncheck "Use global user setting" from Repository-> Repository Settings -> Advanced does the commit author change as expected.
<pre>
/home/USERNAME/SHAREFOLDER 192.168.1.0/24(rw,sync,no_subtree_check)
/ubuntu  *(ro,sync,no_root_squash)
/home    *(rw,sync,no_root_squash)
# replace * with one of the hostname formats.
</pre>
where 'ro' means read only. See [http://www.brennan.id.au/19-Network_File_System.html Linux Home Server Howto]. The '''no_root_squash''' option will not prevent root on a client machine from writing files to the server as root; by default, NFS will map any requests from root on the client to the 'nobody' user on the server. See [https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-14-04 digitalocean].


To start the NFS server:
See [http://blog.bitbucket.org/2011/12/21/mobile-apps-for-bitbucket/ here] for a list of Android apps related to bitbucket.
<syntaxhighlight lang='bash'>
sudo service nfs-kernel-server start
</syntaxhighlight>
 
'''Client part''':
 
PS.
* ''There is no need to enter any password related to the NFS server.''
* See [https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-14-04 digitalocean] for other ways to specify the arguments in </etc/fstab>.
<syntaxhighlight lang='bash'>
sudo apt-get install nfs-common
 
sudo mount example.hostname.com:/ubuntu /mnt/ubuntu
# The mount point directory /mnt/ubuntu must exist.
# or modify the /etc/fstab file
# example.hostname.com:/ubuntu /mnt/ubuntu nfs rsize=8192,wsize=8192,timeo=14,intr
# localip:/sharedfolder /mnt/ubuntu nfs defaults 0 0
 
brb@brb-P45T-A:~$ ps -ef | grep nfs
root      675    2  0 11:16 ?        00:00:00 [nfsiod]
root    14783    2  0 16:51 ?        00:00:00 [nfsv4.0-svc]
brb      14960 13491  0 16:56 pts/0    00:00:00 grep --color=auto nfs
</syntaxhighlight>


=== [https://en.wikipedia.org/wiki/Server_Message_Block CIFS (Common Internet File System)] and [https://en.wikipedia.org/wiki/NT_LAN_Manager NTLMv2 (NT LAN Manager)] ===
= Image =
* https://hpc.nih.gov/docs/transfer.html#mapped
See [[Images|Images]].
* https://wiki.ubuntu.com/MountWindowsSharesPermanently
* https://help.ubuntu.com/community/MountWindowsSharesPermanently
* https://help.ubuntu.com/community/Samba/SambaClientGuide


''Note that this method is most suitable for transferring small files. Users transferring large amounts of data to and from Helix/Biowulf should continue to use scp or sftp.'' ([https://hpc.nih.gov/docs/transfer.html#mapped nih.gov])
= [https://www.gimp.org/ GIMP] =


=== Samba ===
= Reload/Refresh .profile file =
* https://www.howtoforge.com/samba-server-ubuntu-14.04-lts
https://askubuntu.com/a/59127
* [http://www.noobslab.com/2012/03/configure-samba-sharing-between-ubuntu.html Share 'between' ubuntu and Windows]
<pre>
<pre>
sudo apt-get install samba samba-common
. ~/.profile
sudo apt-get install python-glade2
sudo apt-get install system-config-samba
</pre>
Use Dash and search for 'samba'. It will ask for the user's password first. The samba password can also be set by
<pre>
sudo smbpasswd -a USERNAME
</pre>
</pre>
<span style="border: 1px solid black">'''.'''</span> is a '''bash''' builtin and a synonym for source, see man bash.


A non-gui way to configuration samba is adding the following to the end of /etc/samba/smb.conf file, '''sudo nano -w /etc/samba/smb.conf'''
[https://askubuntu.com/a/951009 After changing the .profile file, you have to logout from your account and login, then it will be sourced once automatically.]
<pre>
[brb]
        path = /home/brb
;      writeable = no
;      browseable = yes
        guest ok = yes
</pre>
* [http://www.unixmen.com/howto-install-and-configure-samba-share-in-ubuntu/ Share between ubuntu and linux] On the client file manager, type
<pre>
smb://192.168.1.3/
</pre>
* https://help.ubuntu.com/community/Samba


On Windows PC, go to start and open 'Run' then enter ip with double backslash. Like this (\\192.168.1.3).
= History of commands =
* [http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/ 15 Examples To Master Linux Command Line History]
* [https://www.networkworld.com/article/3537214/tweaking-history-on-linux.html Tweaking history on Linux]


=== Change the default session when using auto login ===
== history command with date and time ==
See [http://askubuntu.com/questions/62833/how-do-i-change-the-default-session-for-when-using-auto-logins this post]. We need to edit the file /etc/lightdm/lightdm.conf. Note that on my Ubuntu 12.04, I have the following desktop options.
* http://www.cyberciti.biz/faq/unix-linux-bash-history-display-date-time/
 
Running the following code once and history will give date and time the next time you issue the '''history''' command.
<pre>
<pre>
$ ls -lt /usr/share/xsessions/
echo 'export HISTTIMEFORMAT="%Y-%m-%d %T "' >> ~/.bashrc
total 16
-rw-r--r-- 1 root root 205 Apr 19  2012 gnome.desktop
-rw-r--r-- 1 root root 188 Apr 19  2012 gnome-shell.desktop
-rw-r--r-- 1 root root 208 Apr 19  2012 ubuntu-2d.desktop
-rw-r--r-- 1 root root 185 Apr 19  2012 ubuntu.desktop
</pre>
</pre>
Note that the original post asks to write the line to ~/.bash_profile but [http://askubuntu.com/questions/121073/why-bash-profile-is-not-getting-sourced-when-opening-a-terminal this is not working in the desktop environment].


=== Debian root user from remote access ===
Note that on zsh, the above method is not supported. We can use '''history -i''' instead. Type ''man zshoptions'' or ''man zshbuiltins'' for more information.
When you login by SSH, then use the username you have chosen when you installed Debian as the root user is disabled for remote logins. Then run the command "su" to become root user. See [https://www.howtoforge.com/tutorial/debian-8-jessie-minimal-server/2/ howtoforget.com].


=== Terminal tab color ===
== Bang bang - Run a command/Fetch parameters from previous ''history'' ==
If we open several tabs in the (GNOME) Terminal, the default color of the active tab is not quite different from the other tabs. We need a solution to change the tab colors.
* http://unixhelp.ed.ac.uk/shell/tcsh_hist3.html
* http://codytaylor.org/2009/09/linux-bang-commands.html


http://askubuntu.com/questions/355297/gnome-terminal-tabs-no-contrast-between-active-and-inactive-tabs
# ^P: Move up through the command history list one command at a time.
# ^N: Move down through the command history list one command at a time.
# '''!!''': Run the previous command. For example, we can run '''sudo !!''' in order to run the previous command with sudo.
# '''!n''': Run command number n (useful)                       
# '''!string''': Run most recent command starting with characters in string (useful). For example, !ls
# !?string: Run most recent command containing characters that match string
# '''!*''': Fetch parameters from last command (useful). For example, if we run "ls /var" first. Then when we run '''stat !*''', it would run ''stat /var''. Or we can run '''cd !*''' and it will cd to /var directory.
# '''!_''': Fetch the last parameter from last command. For example, if we run "ls /var/ /etc" first. Then when we run '''stat $_''', it would run ''stat /etc''. (zsh shell only)
# '''Ctrl + r''' and type a keyword (most useful). Press ctrl + r to scroll the match. This is called reverse i search.
 
For example,
<pre>
<pre>
Solution: edit ~/.config/gtk-3.0/gtk.css (you might have to create it) and add:
!-1
 
!4
TerminalWindow,
!tail
TerminalWindow.background {
</pre>
        background-color: #6e6e6e;
        color: #000000;
}


TerminalWindow .notebook tab {
== Recall commands with reverse-i-search ==
        padding: 2;
Ctrl + r. See [https://www.redhat.com/sysadmin/bash-bang-commands Bash bang commands: A must-know trick for the Linux command line]
        background-color: #6e6e6e;
}


TerminalWindow .notebook tab:active {
To continue with the search, just hit Ctrl + r keys again.
        background-color: #d1d1d1;
}
</pre>
Then close '''ALL''' terminal windows start and test.


=== Install Microsoft Font in linux suite ===
To run a forward search, hit Ctrl + s. [https://unix.stackexchange.com/a/73499 How to cycle through reverse-i-search in BASH?]
[http://www.pcworld.com/article/2863497/how-to-install-microsoft-fonts-in-linux-office-suites.html PCWorld.com]


=== Install language packs ===
== Increase history limit ==
http://unix.stackexchange.com/questions/17574/is-there-a-maximum-size-to-the-bash-history-file
[https://stackoverflow.com/a/12234989 Unlimited Bash History]
<pre>
<pre>
sudo apt-get install language-pack-[cod] language-pack-gnome-[cod] language-pack-[cod]-base language-pack-gnome-[cod]-base
$ echo $HISTSIZE  # $HISTSIZE variable controls how much history is displayed
500
$ export HISTSIZE=1000
$ echo “HISTSIZE=1000” >> ~/.bashrc
 
# $HISTFILESIZE variable controls how many commands are retained in your .bash_history file.
$ echo $HISTFILESIZE
2000
$ wc -l .bash_history
2000 .bash_history
</pre>
</pre>
For example, [cod]=en or [cod]=zh.


=== Change locale language and character set ===
== Not to add to bash history ==
* http://www.shellhacks.com/en/HowTo-Change-Locale-Language-and-Character-Set-in-Linux
[https://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_or_Ubuntu#Configure_MySQL Add a space after the command].
 
It is useful if there is a password in the command.


=== Display Chinese character (from vanilla Debian/Ubuntu system) ===
For example,
* [http://en.wikipedia.org/wiki/Help:Multilingual_support_%28East_Asian%29#Debian-based_GNU.2FLinux Wikipedia]
<pre>
sudo apt-get install fonts-arphic-ukai fonts-arphic-uming
</pre>
* [http://crunchbang.org/forums/viewtopic.php?id=778 crunchbang.org]
<pre>
<pre>
sudo apt-get install language-support-fonts-zh
$ ls ~/            # this won't be recorded in history
# Or
$  ls ~/Downloads/  # this will be recorded in history
sudo apt-get install ttf-arphic-uming ttf-wqy-zenhei
$ history
</pre>
</pre>
* [http://wiki.debian.org.hk/w/Make_Debian_support_Chinese_%28eng%29 wiki.debian.org.hk]
* [https://wiki.debian.org/Fonts wiki.debian.org]


=== Chinese Input ===
== Delete a single command from history ==
[[File:Zhuyin-keyboard.gif|600px]]
* [https://www.cyberciti.biz/faq/delete-command-from-history-linux-unix-osx-bash-shell/ How to delete a single command from history on a Linux/Unix Bash shell]
* [https://opensource.com/article/20/6/bash-history-control Make Bash history more useful with these tips]


http://pinyinjoe.com/linux/ubuntu-12-chinese-setup.htm
To stop adding history entries, you can place a space before the command, as long as you have '''ignorespace''' in your '''HISTCONTROL''' environment variable.


Note: If ibus does not have chewing selection, we should install it first.
You can force Bash to exclude commands starting with empty space by placing this in your .bashrc file:
<pre>
<pre>
sudo apt-get install ibus-chewing
export HISTCONTROL=$HISTCONTROL:ignorespace
</pre>
</pre>


# type 'language' in Dash search (Or click Power button on the top-right corner -> System Settings...) and click 'Language Support' (this may not be installed from (x)Ubuntu automatically. In such case, IBUS will be missing eg Chewing method). The 'Language Support' is under Settings menu in xUbuntu.
== [https://www.howtoforge.com/clear-bash-history/ How to Clear Bash History on Linux] ==
# choose 'IBUS' for keyboard input method. IBUS is under 'System' menu in xUbuntu.
{{Pre}}
# Click 'Install/Remove Languages'. Choose Chinese -> Chewing. Note that Chewing is not the same as Bopomofo. I cannot get used to Bopomofo method.
$ cat /dev/null > ~/.bash_history && history -c && exit
# Settings > Keyboard Input Method > Input method > Select an input method > Show only input methods for your region > Chinese 酷 Chewing. If we cannot find this dialog, we can launch it by '''ibus-setup''' command. If Chewing is not shown as one of Chinese input methods, we can log out and log in the desktop.
</pre>
# Click 'Close' button.


Log out and Log in. Click Keyboard icon on top right corner. Modify its Preferences. Go to 'Input Method' tab. Add Chinese-Chewing and click 'Close' button. We can use Ctrl+Space to switch language input.
== multiple terminals ==
Use ‘’’history -a’’’ to write the history to the file if we do not plan to close the terminal. See [https://www.howtogeek.com/465243/how-to-use-the-history-command-on-linux/ How to use the history command on Linux].


On Ubuntu 13.10, type 'language support' in the Dash. Click 'Install/Remove Languages' and check Chinese. In the 'Keyboard input method system', change from default to 'IBus'. We shall see a keyboard icon on the top right of menu. Click it and choose Text Entry Settings. Add Chinese Chewing input. Then change 'switch to next source using' method to 'Ctrl + Space' by pressing both keys on your keyboard. Bingo!
= Listen to HiChannel internet radio =
Use [http://radiotray.sourceforge.net/ Radio Tray]


Note that do not use 'Text Entry' application (shown as one options when we search 'language'). This application will conflict with ibus.
* http://endroid.blogspot.com/2012/02/listen-hichannel-radio-online-by.html
* http://abcde9990101.blogspot.com/2011/05/ubunturadio-tray.html


If for some reason, ibus-daemon was not started automatically, try the approach [http://askubuntu.com/questions/135548/how-to-add-ibus-to-start-up-applications here] by adding ibus-daemon to the startup application list.
I use it to listen m3u file (VLC also supports it too).


=== /usr/lib/ibus/ibus-ui-gtk3 high memory usage ===
= [http://en.wikipedia.org/wiki/Web_analytics Web Analytics Reporting Tools] =
For some reason, the ubuntu 14.04 is not responsive. Htop shows ibus-ui-gtk3 is the culprit. The [http://askubuntu.com/questions/490317/how-can-i-find-out-what-ibus-daemon-and-ibus-ui-gtk3-are-doing suggestion] is to run
* [http://piwik.org/ Piwik] (open source). [https://www.howtoforge.com/tutorial/how-to-install-piwik-with-nginx-on-ubuntu-15-10/ How to Install Piwik with Nginx on Ubuntu 15.10]
<syntaxhighlight lang="bash">
* [https://www.howtoforge.com/tutorial/how-to-install-matomo-web-analytics-on-centos-7/ How to Install Matomo (formerly Piwik) Web Analytics on CentOS 7]
killall ibus-daemon
* [http://awstats.sourceforge.net/ AWStats]
</syntaxhighlight>
* [http://www.google.com/analytics/ Google Analytics]
After I run this command and wait a few seconds, the memory leak problem is solved.


=== Change time zone ===
= Painting software =
http://wiki.debian.org/TimeZoneChanges
* [https://krita.org/en/ Krita] - professional painting program made by artists that want to see affordable art tools for everyone. [https://www.makeuseof.com/tag/krita-free-gimp-alternative/ Krita Is the Free GIMP Alternative You Should Be Using].
<ul>
<li>[http://pinta-project.com/ Pinta]. It can be install by apt-get command. It works just line Window's paint. Ctr + v to paste an image and save to a file. To crop an image, click the selection tool on the most left hand side (it's a black color on v1.6 but a gray color on v1.7), then select a rectangle. Now click 'Image' > 'Crop to Selection' to finish. [https://itsfoss.com/pinta-new-release/ Pinta New Release After 5 Years. Here’s How to Get it!]
<pre>
<pre>
$sudo dpkg-reconfigure tzdata
sudo add-apt-repository ppa:pinta-maintainers/pinta-stable
sudo apt update
sudo apt install pinta
</pre>
</pre>
The command launches an ncurses based interface which allows arrow keys to be used to select the region specific time zone.
</li>
</ul>
* [http://mtpaint.sourceforge.net/ mtPaint]. It is included in Odroid - xu4 - Lubuntu 14.04. To crop an image, just select an area and click Image > Crop. It can be used to [http://mtpaint.sourceforge.net/handbook/en_GB/chap_A.html take a screenshot] from the desktop by using either the application or through the command line ('''mtpaint -s'''). It will then display the screenshot in the application if you use the command line.
* [http://www.ubuntugeek.com/install-mypaint-on-ubuntu-15-10.html MyPaint]
 
== Take a screenshot (and edit them) ==
See [[#Take_screenshots_.28and_edit_them.29|Take screenshots]].


=== Make script run at boot time with init.d directory ===
= [https://cozy.geigi.de/ Cozy] - audiobook player =
http://www.debian-administration.org/articles/28
* [https://www.linuxuprising.com/2018/09/cozy-is-nice-linux-audiobook-player-for.html Cozy Is A Nice Linux Audiobook Player For DRM-Free Audio Files]
* [https://www.lifewire.com/free-audio-books-3481748 Top 14 Websites For Free Audiobooks]


For example, see [http://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/init-script here] from running a python script for raspberry pi.
= ebook readers =
# Create a script '''/etc/init.d/lcd'''
[https://itsfoss.com/best-ebook-readers-linux 7 Best eBook Readers for Linux]: Calibre, FBReader, Okular, Lucidor, Bookworm, Easy Ebook Viewer and Buka.
# Make the script executable
# Make the script known to the system by using the '''update-rc.d' command
<pre>
sudo update-rc.d lcd defaults
</pre>


=== wireless connection randomly drop off ===
== [http://calibre-ebook.com/download_linux Calibre] - Read ebook in epub format ==
My wireless adapter is TP-LINK, TL-WN722N.
See [[Calibre|Calibre]]


http://askubuntu.com/questions/73607/wireless-connection-keeps-dropping-with-an-intel-3945abg-card
= RSS reader =
<pre>
Some references:
sudo iwconfig wlan0 power off
# [https://itsfoss.com/feed-reader-apps-linux/ 5 Best Feed Reader Apps for Linux]
</pre>
# [https://www.tecmint.com/best-rss-feed-readers-for-linux/ 14 Best RSS Feed Readers for Linux in 2018]. It contains nice screenshots.


[http://linuxplained.com/how-to-fix-wireless-problems-in-ubuntu-1204-precise-pangolin/ 5 Best Linux/Ubuntu compatible USB Wifi cards]:
Some examples:
* [https://hyliu.me/fluent-reader/ Fluent Reader]. Open source. Linux, Windows, macOS.
* [https://www.kde.org/applications/internet/akregator/ Akregator]. KDE based. This is preinstalled in CentOS-KDE under the Internet category. It is also called 'Feed Reader'.
* [https://quiterss.org/ QuiteRSS]. It works on Linux, Windows and MacOS.
* [https://lzone.de/liferea/ Liferea]. GTK based. It is considered one of the best RSS feed readers on Ubuntu Linux. It can synchronize with several online feed managers such as InoReader among others.
* [https://jangernert.github.io/FeedReader/ FeedReader]. Looks nice. Works with several online feed managers.
* [https://newsbeuter.org/ Newsbeuter]: RSS feed in terminal
* [https://github.com/newsboat/newsboat Newsboat]: terminal. [https://www.makeuseof.com/newsboat-feed-reader-for-linux-terminal/ Newsboat: The Best Terminal-Based RSS Feed Reader for Linux]. Not for general use since it assumes the articles are all text-based.
* [http://www.rssowl.org/ RSSOwl]. Depends on Java. Cross platform.
* Firefox and Thunderbird have built-in support for RSS.


*  AirLink101 AWLL6075 Wireless N Mini USB Adapter
= Clear gibberish all over the screen =
*  Medialink – Wireless N USB Adapter – 802.11n
Just type “reset”. See [https://www.cyberciti.biz/tips/bash-fix-the-display.html BASH Fix Display and Console Garbage and Gibberish on a Linux / Unix / macOS]. It is useful, for example, accidentally I run cat command over binary file.
*  ASUS (USB-N13) Wireless-N USB Adapter
*  Panda Mini Wifi (b/g/n) 150Mbps Card
*  TP-Link TL-WN722N 150Mbps High Gain Wireless USB Adapter


To show (USB) wireless adapter information
= Display/screen =
<pre>
== Turn off/on your monitor via command line ==
sudo lshw -C network
* https://systembash.com/how-to-turn-off-your-monitor-via-command-line-in-ubuntu/
sudo lsusb -v
* http://askubuntu.com/questions/62858/turn-off-monitor-using-command-line
iwconfig
{{Pre}}
xset dpms force off # Press any key to turn it on
xset dpms force on
xset -q # check the status of the X server settings
</pre>
 
If we want to turn off/on the screen via ssh, add
{{Pre}}
export DISPLAY=:0.0
</pre>
first before calling the '''xset''' command, or use '-display' argument
{{Pre}}
xset -display :0.0 dpms force off
xset -display :0.0 dpms force on
</pre>
</pre>


To check wifi connection information (SSID, channel, address, frequency, qualiyt, signal level, ...)
== autoxrandr ==
<pre>
Plug your laptop into different monitor setups. https://www.donarmstrong.com/posts/autorandr/
sudo iwlist wlan0 scan
 
== Move a window without clicking the titlebar ==
Hold down the '''Alt''' key and then click in the window anywhere, and move your mouse.
 
== Add new screen/display resolutions ==
* http://ubuntuforums.org/showthread.php?t=1112186 (tested on UDOObuntu 2 beta 2running Ubuntu 14.04 + SainSmart 9" LCD display. The commands (not persistent) are
{{Pre}}
xrandr | grep maximum
gtf 800 480 59.9  # give some output used in the following line
xrandr --newmode "800x480_59.90" 29.53 800 816 896 992 480 481 484 497 -HSync +Vsync
xrandr --addmode "DISP3 BG" 800x480_59.90
xrandr --output "DISP3 BG" --mode 800x480_59.90
</pre>
</pre>
My experience is quality should be at least 50/70 and signal level should be larger than -60dBm.


=== Create an iso file from a CD or HD ===
I cannot find the file /etc/X11/xorg.conf in my UDOObuntu 2 beta 2. It seems this file does not exist anymore. See [http://askubuntu.com/questions/4662/where-is-the-x-org-config-file-how-do-i-configure-x-there this post] about how to re-create it.
Method 1 (Better than Method 2). No need to umount the cdrom.
 
<pre>
== Wayland ==
mkisofs -o /tmp/DVD.iso /tmp/directory/
* '''echo $XDG_SESSION_TYPE''' to check whether X11 or Wayland is in use
* To change from wayland to X11:
** Method 1: log out, click the username, choose Xorg and type the password
** Method 2:
:<syntaxhighlight lang='bash'>
sudo nano /etc/gdm3/custom.conf
</syntaxhighlight>Change the line ''' WaylandEnable=true''' to '''WaylandEnable=false''' And restart the system1.
* Ubuntu 22.04 LTS with GNOME 42 and Wayland as the default
* [https://liliputing.com/2018/08/linux-on-the-gpd-pocket-2-ubuntu-debian-and-fedora.html Linux on the GPD Pocket 2 (Ubuntu, Debian, and Fedora)]
** “xrandr -o right” command can be used to rotate the screen
** But it does not work in Fedora because Fedora uses the Wayland display server rather than xserver.
* [https://www.linuxuprising.com/2019/11/how-to-automate-repetitive-typing-text.html How To Automate Repetitive Typing (Text Expansion) With AutoKey On Linux]. AutoKey is an X11 application, it won't work properly if you use Wayland (e.g. Fedora uses Wayland by default; if you want to use Xorg you must logout, and select "GNOME on Xorg" from the cog icon next to the Sign In button).
* [https://www.tecmint.com/configure-xorg-as-default-gnome-session/ How to Configure Xorg as Default GNOME Session in Fedora]
* [https://unix.stackexchange.com/a/325972 How to know whether Wayland or X11 is being used]
{{Pre}}
loginctl show-session $(awk '/tty/ {print $1}' <(loginctl)) -p Type | awk -F= '{print $2}'
</pre>
</pre>
to make an ISO from files on your hard drive.


Method 2.
== export DISPLAY ==
Make sure the cdrom is NOT mounted. Type '''mount''' to confirm it. If cd was mouted automatically unmout it with umount command:
<ul>
like '''umount /dev/cdrom''' or '''umount /mnt/cdrom'''. Note that no extra forward slash after /dev/cdrom for the command below.
<li>[https://askubuntu.com/a/432257 What is the $DISPLAY environment variable?]
The value of the display environment variable is:
<pre>
<pre>
dd if=/dev/cdrom of=~/DVD.iso
hostname:displaynumber.screennumber
</pre>
<li>If we want to run a GUI app on a remote computer (such as Raspberry Pi/Beaglebone Black) and show the GUI app on the remote computer's screen using ssh, we can issue the following command before running the app.
{{Pre}}
export DISPLAY=:0.0
</pre>
</pre>
</ul>


We can mount the iso file to a directory to check the iso file content is correct.
= See which groups you belong to, id & group commands =
<pre>
<pre>
mount -t iso9660 -o loop,ro DVD.iso /mnt
id <username>
groups
groups <username>
</pre>
</pre>


=== Have fun with /etc/hosts file ===
== Main Types of User Accounts on Linux ==
su -c "nano /etc/hosts"
[https://www.makeuseof.com/types-of-user-accounts-on-linux/ The 4 Main Types of User Accounts on Linux]:
* Superuser Account
* Regular Accounts
* System Accounts (Core OS functionality, eg root, bin, sys, daemon) '''awk -F: '$3 <= 100 {print $1, $3, $7}' /etc/passwd''' Note that the third field is the user ID (UID). System accounts generally have UIDs below 100 (though this threshold may vary slightly depending on your distribution).
* Service Accounts (eg SQL, apache).
 
== List all user groups ==
[https://www.makeuseof.com/how-to-list-all-user-groups-on-linux/ How to List All User Groups on Linux]
To see a list of groups
<pre>
<pre>
74.125.67.100  DNS_NAME1 DNS_NAME2
cat /etc/group
# OR
getent group
</pre>
</pre>
Note that "getenv group" Lists groups from all configured sources, including both local and networked sources, depending on your system’s NSS (Name Service Switch) configuration (in /etc/nsswitch.conf).


=== Find a file based on file name ===
== finger: show user information ==
<syntaxhighlight lang='bash'>
finger USERNAME
$ find . -iname '*.txt'
</syntaxhighlight>


It also works for searching files on subdirectories.
= groupadd, chgrp, usermod, ACL (access control lists) =
<syntaxhighlight lang='bash'>
* [https://www.cyberciti.biz/faq/howto-linux-add-user-to-group/ Linux Add User To Group Using Command-Line]: '''useradd'''
$ find . -name transcripts.gtf
* [http://www.tecmint.com/create-a-shared-directory-in-linux/ Create a Shared Directory for All Users in Linux]
./RH_bio/transcripts.gtf
* [https://www.tecmint.com/give-read-write-access-to-directory-in-linux/ Assign Read/Write Access to a User on Specific Directory in Linux]
./dT_ori/transcripts.gtf
* [https://www.howtoforge.com/linux-chgrp-command/ Linux Chgrp Command for Beginners (5 Examples)]
./dT_tech/transcripts.gtf
 
./dT_bio/transcripts.gtf
{{Pre}}
./RH_ori/transcripts.gtf
sudo mkdir -p /var/www/reports/
./RH_tech/transcripts.gtf
sudo groupadd project
</syntaxhighlight>


Find files and execute something (google: find --exec)
sudo usermod -a -G project tecmint
<syntaxhighlight lang='bash'>
sudo chgrp -R project /var/www/reports/
$ find ./ -name "*.tar.gz" -exec tar zxvf {} \;
sudo chmod -R 2775 /var/www/reports/
</syntaxhighlight>
</pre>


Find files modified in one day.
create more system users and add them to the directory group as follows:
<syntaxhighlight lang='bash'>
{{Pre}}
$ find . -mtime -1
sudo useradd -m -c "Aaron" -s/bin/bash -G project aaron
</syntaxhighlight>
sudo useradd -m -c "John" -s/bin/bash -G project john
sudo useradd -m -c "Ravi" -s/bin/bash -G project ravi


Find files modified in one day and contain string 'est'
sudo mkdir -p /var/www/reports/aaron_reports
<syntaxhighlight lang='bash'>
sudo mkdir -p /var/www/reports/john_reports
$ find . -mtime -1 -exec grep --with-filename est {} \;
sudo mkdir -p /var/www/reports/ravi_reports
</syntaxhighlight>
</pre>


If the search directory is not the current directory, we need to add a forward slash to the directory name.
== See who's in a group ==
<syntaxhighlight lang='bash'>
<pre>
$ find ~/Desktop -iname '*.txt' # Not working
grep '^group_name_here:' /etc/group
$ find ~/Desktop/ -iname '*.txt' # Working
</syntaxhighlight>


The [http://content.hccfl.edu/pollock/unix/findcmd.htm following example] shows we can list multiple search criteria. The “‑r” option in tar appends files to an archive. '''xargs''' is a handy utility that converts a stream of input (in this case the output of find) into command line arguments for the supplied command (in this case tar, used to create a backup archive).
finger USERNAME # See more detail about a user
<syntaxhighlight lang='bash'>
</pre>
find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar
</syntaxhighlight>


=== '''grep''': Find a file by searching contents ===
== Add a standard user to '''sudo''' group ==
<pre>
This is useful on Debian distribution where a new user does not have the sudo power. First log in as root,
grep -r -i "Entering" ~/Downloads/R-3.0.0/
{{Pre}}
# usermod -aG sudo username
</pre>
</pre>
where '''-r''' means recursively searching the directory and '''-i''' means case insensitive.


We can also display the row numbers for matches by using the '''-n''' parameter in grep.
= Shared library management =
<pre>
http://www.cyberciti.biz/tips/linux-shared-library-management.html
# What variants appear in dbsnp
 
grep -n 'rs[0-9]' XXX.vcf
# ldconfig : Updates the necessary links for the run time link bindings.
# ldd : Tells what libraries a given program needs to run.
# ltrace : A library call tracer.
# ld.so/ld-linux.so: Dynamic linker/loader.
 
= Log files =
* [https://www.digitalocean.com/community/articles/how-to-view-and-configure-linux-logs-on-ubuntu-and-centos DigitalOcean]
* [https://www.debugpoint.com/2021/08/monitor-log-files-real-time/ How to Monitor Log Files in Real Time in Linux [Desktop and Server]]
{{Pre}}
$ ls -lt /var/log
</pre>
</pre>


To exclude lines with a pattern, using the '''-v''' parameter.
== ssh log files: '''/var/log/auth.log''' ==
* /var/log/syslog: it is useful to use '''tail -f /var/log/syslog''' to show the log in real time
* /var/log/auth.log: it includes ssh log in information and lots of CRON sessions opened and closed ''every minutes''.
 
And
* [https://askubuntu.com/questions/465544/why-do-i-see-a-cron-session-opening-and-closing-every-hour-in-var-log-auth-log Why do I see a CRON session opening and closing every hour in /var/log/auth.log?]
* [https://ubuntuforums.org/showthread.php?t=1256801 remove cron from /var/log/auth.log]
* [https://www.linuxquestions.org/questions/linux-security-4/what-the-%24-%40-is-pam_unix-cron-session-doing-every-ten-minutes-var-log-auth-log-702381/ What the %$#@ is pam_unix (cron:session) doing every ten minutes? (/var/log/auth.log)]
 
== lnav (The Logfile Navigator) ==
[https://www.debugpoint.com/monitor-log-files-real-time/ How to Monitor Log Files in Real Time in Linux (Desktop and Server) ]. '''sudo apt install lnav; sudo lnav'''
 
== Apache log ==
* /var/log/apache2/error.log (small 83K). Useful to troubleshoot errors/crashes of Apache.
<pre>
<pre>
# How many variant were called
grep "May 08" /var/log/apache2/error.log
grep -v "^#" XXX.vcf | head
</pre>  
</pre>
* /var/log/apache2/access.log (large 10M)
 
== mail ==
/var/log/maillog


To show only matched filenames, using the '''-l''' paramter.
== Logrotate ==
<pre>
[https://www.cloudsavvyit.com/176/how-to-setup-logrotate-on-linux-to-keep-your-server-from-running-out-of-space/ How to Setup Logrotate on Linux (to Keep Your Server from Running Out of Space)]
grep -l "iterator" *.cpp
</pre>


https://www.howtoforge.com/tutorial/linux-grep-command/ gives more examples
= uprecords command =
* Using grep to search only for words  ("-w" option)
* [https://linuxtldr.com/uprecords-command/ Check the Linux Uptime History Using the Uprecords]
* Using grep to search two different words  (egrep -w 'word1|word2' /path/to/file)
* [https://linuxhandbook.com/uptime-command/ How to Check Uptime of Your Linux Server]
* Count line for matched words  ("-c" option)
* Grep invert match ("-v" option)
* How to list only the names of matching files ("-l" option)


A GUI version of a tool to search files is [http://searchmonkey.embeddediq.com/ '''searchmonkey'''] (open source, Linux, Windows). On Ubuntu, we install it by
= '''uptime''' command =
<pre>
{{Pre}}
sudo apt-get install searchmonkey
uptime
watch -n 60 uptime
</pre>
</pre>
It is also useful to change the settings so we can click a filename and open it in the desired text editor. To do that, go to Settings -> Preferences -> System Call -> Text Editor. I enter 'geany' since I want to use geany to open my C programs. '''Note'''. the v2.0 source code needs to be built using i386 gcc library and Qt 4.8.x. Still, I cannot get rid of some errors coming from the source code.


Summary of '''find''' and '''grep''' commands:
Windows
{| class="wikitable"
* [https://www.windowscentral.com/how-check-your-computer-uptime-windows-10#check_pc_uptime_cmd How to check PC uptime using Command Prompt]
! Command
* [https://www.bettertechtips.com/windows/check-uptime-windows-10/ 4 Ways to Check the System Uptime in Windows 10]
! Examples
* [https://mivilisnet.wordpress.com/2017/07/21/how-to-find-the-windows-system-uptime-using-the-command-line/ How to find the Windows system uptime using the command line]
|-
| find
| find [DIRECTORY]  -iname '*.txt'
find [DIRECTORY] -maxdepth 2 -iname *.php


find -name '*.php' -o -name '*.txt'  # OR operator
== Find out from the logs what caused system shutdown? ==
|-
[https://unix.stackexchange.com/a/10522 How to find out from the logs what caused system shutdown?]
| grep
| grep -r -i "check_samtools" DIRECTORY/
dpkg -l libgtk* | grep  '^i'
|}


=== Mount a remote file system over ssh ===
== Get notified when a system is rebooted ==
* [https://www.digitalocean.com/community/tutorials/how-to-use-sshfs-to-mount-remote-file-systems-over-ssh this article] on digitalocean.com.
[https://atinkerersblog.wordpress.com/2014/07/26/get-notified-when-your-raspberry-pi-is-booted-with-pushbullet/ Get Notified When Your Raspberry Pi is Booted with Pushbullet]. This makes use of '''/etc/rc.local''' file. If it does not work, we can use cron to run a command at startup; see [[Raspberry#Sending_an_email_on_boot|sending an email on boot]].
* [http://linuxlove.eu/quick-tip-mounting-remote-linux-directory-windows-linux-ssh/ linuxlove.eu]


The trick is to use '''sshfs''' tool.
= '''timeout''' command =
* https://www.howtoforge.com/linux-timeout-command/
* https://www.howtogeek.com/423286/how-to-use-the-timeout-command-on-linux/


On Ubuntu
= Linux command similar to ''top'' to show hard disk activity =
<pre>
Use '''iotop'''. On ubuntu, we can use sudo apt-get install to install it. Use '''sudo iotop''' to launch it. Use '''-o''' to show processes that are actually doing IO.
# Install the program
{{Pre}}
sudo apt-get install sshfs
sudo apt-get install iotop


# Mount the file system
sudo iotop -o -u $USER
sudo mkdir /mnt/droplet <--replace "droplet" whatever you prefer
</pre>
sudo sshfs [email protected]:/ /mnt/droplet


# Unmount the file system
Another program is '''iostat''' and the '''-d''' (disk) option. The '''-x''' option will display extension I/O status.
sudo umount /mnt/droplet
<pre>
 
sudo apt-get install sysstat
# Permanently Mounting the Remote File System
iostat -dx 5 # every 5 seconds
sudo nano /etc/fstab
sshfs#[email protected]:/ /mnt/droplet
</pre>
</pre>
[http://www.thegeekstuff.com/2011/07/iostat-vmstat-mpstat-examples/ 24 iostat, vmstat and mpstat Examples for Linux Performance Monitoring]


=== Nautilus (File Manager) ===
= curl and wget =
==== Undo Ctrl+L ====
See [[Curl|Curl]].
Press ESC.


==== Mount another Linux system in Nautilus ====
= Torrent =
Very easy. Check out
== [https://github.com/kryptxy/torrench Torrench] ==
[http://www.howtogeek.com/203432/how-to-access-ftp-and-webdav-sites-in-any-operating-systems-file-manager/ howtogeek.com]
[https://fossbytes.com/review-torrench-download-torrents-using-terminal-linux/ Torrench: How To Search And Download Torrent Files Using Terminal (Linux, Mac, Windows)]


==== Create a desktop shortcut ====
== aria2 - command line downloader supports torrents and multi-connection ==
Navigate to your application in Nautilus. Right-click, select "Make Link". Then drag shortcut to your desktop. Works in Ubuntu 12.04.
[http://www.2daygeek.com/aria2-command-line-download-utility-tool/ aria2 command examples]


=== Mount iso file ===
The '''-x''' argument helps a little bit. Download a file 112MB; see https://www.archlinux.org/download/
<pre>
<pre style="white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* IE 5.5+ */ " >
$ sudo mkdir /mnt/iso
$ time aria2c  http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 16 seconds
$ sudo mount -o loop /tmp/file.iso /mnt/iso
$ time aria2c -x10 http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 11 seconds
$ sudo umount /mnt/iso
</pre>
</pre>


=== Check ubuntu version from command line ===
= Axel =
http://www.howtogeek.com/206240/how-to-tell-what-distro-and-version-of-linux-you-are-running/
It can create an unlimited number of worker threads to download any kind of data.
See https://www.beginnersheap.com/top-5-command-line-download-accelerators-linux/


<pre>
= [http://lftp.yar.ru/ lftp] =
lsb_release -a
* [http://www.linuxquestions.org/questions/linux-software-2/command-line-ftp-client-94510/ It supports FXP (site-to-site transfers) and dropping to background]
# OR
* [https://www.cyberciti.biz/tips/linux-unix-download-accelerator.html How to use lftp to accelerate ftp/https download speed on Linux/UNIX]. It can launch several commands in parallel in the background.
cat /etc/issue
# OR
cat /etc/*release
# check kernel version
uname -r
# check 32/64 bit kernel
uname -a
</pre>


=== keyboard shortcuts ===
= Apply a patch to source code =
Go to keyboard app to change the settings. Note: '''Super''' key is also Windows key. Use 'Backspace' key to disable a shortcut.
* http://www.cyberciti.biz/faq/appy-patch-file-using-patch-command/.
* http://www.thegeekstuff.com/2014/12/patch-command-examples/
* [https://www.howtogeek.com/415442/how-to-apply-a-patch-to-a-file-and-create-patches-in-linux/ How to Apply a Patch to a File (and Create Patches) in Linux]


* List from [https://help.ubuntu.com/community/KeyboardShortcuts ubuntu.com]
For example [https://groups.google.com/forum/#!topic/tuxedo-tools-users/BVNDDmInU0A Tophat 2.0.12 compatibility with Samtools 1.0],
* Super: Open the Dash. Press and hold it to see a cheat sheet with a bunch of other nifty shortcuts.
{{Pre}}
* Super + Number: Open the application that is at that position in the dock
$ ls
* '''Alt + Mouse''': Move an application. Useful if an application's title bar is too high.
support_for_tophat_1.patch  tophat-2.0.12  tophat-2.0.12.tar.gz
* Alt + F2: Run an application by typing its name in the box which appears (same function as the Super key).  
* Alt + Space: Activate the window menu. Not useful so I disable it.
* Ctrl + Super + D: To minimize all windows
* Ctrl + Alt + Arrows: move to another workspace
* Ctrl + Alt + Shift + Arrows: move current application to another workspace


On Xubuntu,
$ grep -r -i "check_samtools" tophat-2.0.12/
* Alt + F1 (Ctrl + ESC): Application menu.
tophat-2.0.12/src/tophat.py:def check_samtools():
* Alt + F2 (Super + R): Application Finder.
tophat-2.0.12/src/tophat.py:        check_samtools()


=== [http://nebc.nerc.ac.uk/tools/bio-linux BioLinux] ===
$ cp support_for_tophat_1.patch tophat-2.0.12/src/
Bio-Linux 7.0 (2012/11/21) screenshot.  
$ cd tophat-2.0.12/src/
 
$ patch tophat.py < support_for_tophat_1.patch
Biolinux can be installed in two ways.  
patching file tophat.py
# One is to download iso image file. http://nebc.nerc.ac.uk/downloads/
Hunk #1 succeeded at 1540 (offset 3 lines).
# The other way is to install Bio-linux software/package by using apt-get install method. See http://nebc.nerc.ac.uk/tools/bio-linux/other-bl-docs/package-repository
Hunk #2 succeeded at 1563 (offset 3 lines).
 
</pre>
[[File:BioLinux.png|100px]]


==== Check Biolinux version ====
= IP address fundamental =
<pre>
http://www.howtogeek.com/133943/geek-school-learning-windows-7-ip-addressing-fundamentals/.  
cat /etc/bio-linux.version  # 8.0.5 as of June 2015
</pre>


==== Installation ====
There are three classes for private IP ranges.
* Latest version iso or ova.
* 1-126.0.0.0 from Class A
** http://distrowatch.com/table.php?distribution=biolinux
* 128-191.0.0.0 from Class B
** http://distro.ibiblio.org/bio-linux/iso/ US mirror
* 192-223.0.0.0 from Class C


* [http://environmentalomics.org/bio-linux-installation/ Command line] based on Ubuntu 14.04 or from Biolinux 7.
[[#Subnet|Subnet]]
<pre>
wget -qO- http://nebc.nerc.ac.uk/downloads/bl8_only/upgrade8.sh | sudo sh
</pre>
This takes a long long time.


==== Software list ====
= Gateway IP address =
* http://environmentalomics.org/bio-linux-software-list/
[https://ostechnix.com/find-default-gateway-linux/ How To Find Default Gateway IP Address In Linux And Unix From Commandline]


==== FAQ ====
= Get internal IP address =
* http://nebc.nerc.ac.uk/nebc_website_frozen/nebc.nerc.ac.uk//tools/bio-linux-7/bio-linux-faq
{{Pre}}
$ hostname -I


==== Sample Data ====
$ ifconfig # also works on Android through Termux
Did not find them useful.
<pre>
brb@biolinux[brb] ls Desktop/Sample\ Data/                                                        [10:05AM]
act      cytoscape              glimmer3      mrbayes            peptide_seqs      splitstree
artemis  dendroscope            happy        mspcrunch          phylip            squint
blast    dotter                  hmmer        multiple_alignment qiime              t-coffee
blast+    dust                    jalview      mummer              rasmol            tree-puzzle
blixem    fasta                  jprofilegrid  muscle              rdp_classifier    treeview
cap3      fastDNAml              mesquite      mview              readseq
catchall  forester-archaeopteryx  mira          njplot              samtools
clustal  gap4                    mothur        nucleotide_seqs    sanger_tracefiles
brb@biolinux[brb] ls Desktop/Sample\ Data/fasta/                                                  [10:05AM]
bovgh.seq        hahu.aa      mgstm1.e05          mgstm1.nt1r  myosin_bp.aa  oohu.raa
bovprl.seq      hsgstm1b.gcg  mgstm1.eeq          mgstm1.nts  n0.aa        prio_atepa.aa
egmsmg.aa        hsgstm1b.seq  mgstm1.esq          mgstm1.raa  n1.aa        prot_test.lib
grou_drome.pseg  humgstd.seq  mgstm1.gcg          mgstm1.rev  n2.aa        prot_test.lseg
gst.nlib        lcbo.aa      mgstm1_genclone.seq  mgstm1.seq  n2_fs.lib    qrhuld.aa
gst.seq          m1r.aa        mgstm1.lc            mgtt2_x.seq  n2s.aa        sql
gstt1_drome.aa  m2.aa        mgstm1.nt            ms1.aa      n2t.aa        titin_hum.aa
gstt1_pssm.asn1  mchu.aa      mgstm1.nt1          mu.lib      n_fs.lib      titin_hum.seq
gtm1_human.aa    mgstm1.3nt    mgstm1.nt12r        musplfm.aa  ngt.aa        xurt8c.aa
gtt1_drome.aa    mgstm1.aa    mgstm1.nt13          mwkw.aa      ngts.aa      xurt8c.lc
h10_human.aa    mgstm1.aaa    mgstm1.nt13r        mwrtc1.aa    oohu.aa      xurtg.aa
</pre>
</pre>
* https://www.raspberrypi.org/documentation/remote-access/ip-address.md
== Private/internal/local IP/network ==
https://en.wikipedia.org/wiki/IPv4#Private_networks


==== CloudBioLinux ====
* 10.0.0.0 – 10.255.255.255
* http://cloudbiolinux.org/
* 172.16.0.0 – 172.31.255.255
* https://github.com/chapmanb/cloudbiolinux
* 192.168.0.0 – 192.168.255.255


=== Apache configuration ===
There are other special-use addresses for private networks
https://help.ubuntu.com/11.10/serverguide/httpd.html
* 100.64.0.0 to 100.127.255.255 (similar to private IP addresses like 192.168.x.x or 10.x.x.x)


=== Install Nginx as Reverse Proxy for Apache ===
= Get external IP address =
* [https://en.wikipedia.org/wiki/Reverse_proxy Reverse proxy]
Using a browser: Google.com and type "my ip"
* https://www.howtoforge.com/tutorial/how-to-install-nginx-as-reverse-proxy-for-apache-on-ubuntu-15-10/


=== Tomcat ===
[https://opensource.com/article/18/5/how-find-ip-address-linux How to find your IP address in Linux]
* [http://www.ubuntugeek.com/install-tomcat-8-on-ubuntu-15-10-server.html Install Tomcat 8 on Ubuntu]


=== GPU ===
[https://askubuntu.com/a/145017 Command for determining my public IP?] '''wget -qO- https://ipecho.net/plain ; echo '''
http://www.binarytides.com/linux-get-gpu-information/


GPU info
[https://www.2daygeek.com/linux-command-find-check-domain-ip-address/ 5 Commands to Find the IP Address of a Domain in the Linux Terminal]
<syntaxhighlight lang='bash'>
$ lspci -vnn | grep VGA -A 12
# OR
$ lshw -numeric -C display
</syntaxhighlight>


To check hardware acceleration
https://github.com/jakewmeyer/Geo (one shell script)
<syntaxhighlight lang='bash'>
$ glxinfo | grep OpenGL
</syntaxhighlight>


Under Ubuntu-Unity, we can search Additional Drivers to install propriety party drivers instead of using X.org.
[https://www.makeuseof.com/get-public-ip-address-in-linux/ How to Find the Public IP Address on a Linux System]


=== Device manager ===
It seems there is no way to get the external IP address without not using external services.
By default, ubuntu does not provide any graphical tool like device manager on Windows. A very close one is '''[http://ezix.org/project/wiki/HardwareLiSter lshw]''' (hardware lister). A GUI tool based on it is called '''lshw-gtk''' (seems not as informative as the command line one) and can be installed by ''sudo apt-get install lshw-gtk'' in Ubuntu/Debian or ''yum install lshw'' in Red Hat/Fedora/CentOS.
{{Pre}}
host myip.opendns.com resolver1.opendns.com
# Look for the bottom line output  myip.opendns.com has address XXX.XX.XX.XXX


As you can see the line containing 'display' shows the motherboard (P45T-A), CPU (Intel Core 2 Duo E8400), graphical card (GeForce 9400 GT in this case), et al.
# https://unix.stackexchange.com/a/81699
<pre>
sudo apt-get install dnsutils
brb@brb-P45T-A:~$ sudo lshw -short
dig +short myip.opendns.com @resolver1.opendns.com
H/W path        Device      Class      Description
# OR
====================================================
curl ifconfig.me  # by google
                            system      P45T-A (To Be Filled By O.E.M.)
                # also works on Android through Termux
/0                          bus        P45T-A
#
/0/0                        memory      64KiB BIOS
curl http://ipecho.net/plain; echo
/0/4                        processor  Intel(R) Core(TM)2 Duo CPU    E8400  @
# OR
/0/4/5                      memory      64KiB L1 cache
curl ipv4.ipogre.com    
/0/4/6                      memory      6MiB L2 cache
/0/f                        memory      8GiB System Memory
/0/f/0                      memory      2GiB DIMM DDR2 Synchronous 800 MHz (1.2
/0/f/1                      memory      2GiB DIMM DDR2 Synchronous 800 MHz (1.2
/0/f/2                      memory      2GiB DIMM DDR2 Synchronous 800 MHz (1.2
/0/f/3                      memory      2GiB DIMM DDR2 Synchronous 800 MHz (1.2
/0/100                      bridge      4 Series Chipset DRAM Controller
/0/100/1                    bridge      4 Series Chipset PCI Express Root Port
/0/100/1/0                  display    G96 [GeForce 9400 GT]
/0/100/1a                    bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1a.1                  bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1a.2                  bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1a.7                  bus        82801JI (ICH10 Family) USB2 EHCI Contro
/0/100/1b                    multimedia  82801JI (ICH10 Family) HD Audio Control
/0/100/1c                    bridge      82801JI (ICH10 Family) PCI Express Root
/0/100/1c/0      eth0        network    AR8121/AR8113/AR8114 Gigabit or Fast Et
/0/100/1c.3                  bridge      82801JI (ICH10 Family) PCI Express Root
/0/100/1c.3/0    wlan0      network    AR93xx Wireless Network Adapter
/0/100/1c.4                  bridge      82801JI (ICH10 Family) PCI Express Root
/0/100/1c.4/0                storage    JMB361 AHCI/IDE
/0/100/1c.4/0.1              storage    JMB361 AHCI/IDE
/0/100/1d                    bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1d.1                  bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1d.2                  bus        82801JI (ICH10 Family) USB UHCI Control
/0/100/1d.7                  bus        82801JI (ICH10 Family) USB2 EHCI Contro
/0/100/1e                    bridge      82801 PCI Bridge
/0/100/1f                    bridge      82801JIR (ICH10R) LPC Interface Control
/0/100/1f.2                  storage    82801JI (ICH10 Family) 4 port SATA IDE
/0/100/1f.3                  bus        82801JI (ICH10 Family) SMBus Controller
/0/100/1f.5                  storage    82801JI (ICH10 Family) 2 port SATA IDE
/0/1            scsi0      storage   
/0/1/0.0.0      /dev/sda    disk        250GB Samsung SSD 840
/0/1/0.0.0/1    /dev/sda1   volume      224GiB EXT4 volume
/0/1/0.0.0/2    /dev/sda2  volume      8190MiB Extended partition
/0/1/0.0.0/2/5  /dev/sda5  volume      8190MiB Linux swap / Solaris partition
/0/1/0.1.0      /dev/sdb    disk        2TB ST2000DM001-9YN1
/0/1/0.1.0/1    /dev/sdb1  volume      1863GiB EXT4 volume
/0/2            scsi2      storage   
/0/2/0.0.0      /dev/cdrom  disk        DVDRAM GH24NS90
/1                          power      Nikon Ultra Plus
/2                          power      To Be Filled By O.E.M.
</pre>
</pre>
 
To store my IP in a shell variable
For storage part, ubuntu provides a graphical tool. See "disk utility" on gnome based ubuntu or search for "[https://live.gnome.org/Design/Apps/Disks disk]" in launcher.
{{Pre}}
 
myip="$(dig +short myip.opendns.com @resolver1.opendns.com)"
=== Set static IP - /etc/network/interfaces===
echo "My WAN/Public IP address: ${myip}"
<syntaxhighlight lang='bash'>
root@debian:~# cat /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
</syntaxhighlight>
Now edit the file  /etc/network/interfaces
<pre>
# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.1.3
gateway 192.168.1.1
netmask 255.255.255.0
network 192.168.1.0                # Optional
broadcast 192.168.1.255            # Optional
dns-nameservers 192.168.1.1 8.8.8.8 # Or skip 192.168.1.1
</pre>
</pre>


After it, restart the network by issuing
The above only gives the IP. The following method gives geo information too.
<syntaxhighlight lang='bash'>
{{Pre}}
/etc/init.d/networking restart
curl ipinfo.io # ifconfig.me, icanhazip.com, ipecho.net/plain, ifconfig.co
</syntaxhighlight>
# OR give a specific IP (domain name does not work)
OR
curl ipinfo.io/216.58.194.46
sudo reboot


Note: It does not work by editing /etc/resolv.conf since this file will be overwritten.
{
 
  "ip": "216.58.194.46",
=== Change IP address from the command line ===
  "hostname": "dfw25s12-in-f14.1e100.net",
<pre>
  "city": "Mountain View",
/sbin/ifconfig eth0 192.168.1.17 netmask 255.255.255.0 up
  "region": "California",
/sbin/ifconfig eth0
  "country": "US",
  "loc": "37.4192,-122.0574",
  "org": "AS15169 Google Inc.",
  "postal": "94043"
}
</pre>
</pre>


=== [https://help.ubuntu.com/community/UFW ufw (uncomplicated firewall)] ===
== IP geolocation ==
The default firewall configuration tool for Ubuntu is '''ufw'''. Developed to ease '''iptables''' firewall configuration, ufw provides a user friendly way to create an IPv4 or IPv6 host-based firewall. By default UFW is disabled.  
Test url: ubuntu.mirrors.pair.com
* https://iplocation.net
* command line - input is an IP address
:<syntaxhighlight lang='bash'>
curl https://ipapi.co/8.8.8.8/json/


Suppose I have a virtual machine running a web server at port 8888 (The vm may be initialized by the Vagrant command). I can access the webpage from my host machine using http://localhost:8888.  
curl https://ipinfo.io/8.8.8.8
 
</syntaxhighlight>
Now I want the web page to be accessible from other local machines. We can use the '''ufw''' command to enable the firewall wall and open ports for certain services.
* command line - input is a web address
 
:<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
IP_ADDRESS=$(dig +short example.com)
sudo ufw allow 8888/tcp
curl https://ipapi.co/$IP_ADDRESS/json/
sudo ufw show added
sudo ufw enable
sudo ufw status
 
nmap localhost
</syntaxhighlight>
</syntaxhighlight>
* https://www.ipligence.com/geolocation
* http://www.ipfingerprints.com/
* http://ip-api.com/ (it shows your IP, internal IP, OS, browser/user-agent, DNS server from outside?). The final query URL is simple; for example http://ip-api.com/#ubuntu.mirrors.pair.com
* [https://ipstack.com/ ipstack]. [https://www.makeuseof.com/tag/ip-geolocation-api-ipstack/ How to Use the IPStack API for IP Geolocation Lookups]. 10,000 searches per month for free.
* [https://www.makeuseof.com/tag/ip-geolocation-api-tool/ The Free IP Geolocation API Is a Valuable Webmaster Tool]


Now I can go to another machine, open a browser at http://hostip:8888/. I should be able to get the same result as I got from the host machine.
= Domain, WHOIS =
<ul>
<li>[https://www.whois.net/ WHOIS LOOKUP]. For example, consider "r-pkg.org" domain,
<ul>
<li>The 'Sponsoring Registrar' shows who is the sponsoring registrar (eg GoDaddy.com). </li>
<li>The 'Registrant Name' shows who registered this domain. </li>
<li>Command Line Interface.
{{Pre}}
sudo apt-get install whois
whois r-pkg.org
</pre>
</li>
</ul>
</li>
</ul>
* [https://www.makeuseof.com/best-websites-free-whois-information/ The 9 Best Websites to Look Up WHOIS Information for Free]
* [http://ip-lookup.net/index.php IP-Lookup]. For example, consider "r-pkg.org" domain.
** The linux command line tool 'ping' shows the ip address.
** When we use the ip address to search in the IP-Lookup, the '''IP owner info''' > 'Organization' or 'OrgName' field shows the owner of this IP (eg Digital Ocean, Inc).
** The '''Domain owner info''' there gives the same (or less) information as [https://www.whois.net/ WHOIS LOOKUP].
* [http://www.whoishostingthis.com/ WhoIsHostingThis] or [https://www.webhostinghero.com/who-is-hosting/ webhostinghero] (the returned result will be like Amazon, GoDaddy, CloudFlare, Github, Verizon, etc).


Other things '''ufw''' can do:
= Subnet =
* Allow/Deny by ports and (optional) protocols
[http://en.wikipedia.org/wiki/IPv4_subnetting_reference IPv4]
* Allow/Deny by service name
* Disable ping requests.  
* Allow by specific IP
* Allow by subnet
* Allow by specific port and IP address
* Deny by certain IP address
* Deny by certain IP address and certain port


=== DNStracer ===
* Class A: 255.0.0.0 or /8;
http://www.ubuntugeek.com/dnstracer-trace-dns-queries-to-the-source.html
* Class B, 255.255.0.0 or /16;
* Class C, 255.255.255.0 or /24.  


=== Dyndns ===
For example, in the subnet 192.168.5.0/255.255.255.0 (192.168.5.0/24) the identifier 192.168.5.0 commonly is used to refer to the entire subnet.  
See https://help.ubuntu.com/community/DynamicDNS


nano '''/etc/ddclient.conf'''
In the /16 subnet 192.168.0.0/255.255.0.0, which is equivalent to the address range 192.168.0.0–192.168.255.255
<pre>
daemon=600
protocol=dyndns2
use=web, web=checkip.dyndns.com, web-skip='IP Address'
server=members.dyndns.org
login=YOURNAME
password='YOURPASSWORD'
taichi.selfip.net
</pre>
And run ''' ddclient -daemon=0 -debug -verbose -noquiet''' to confirm it is working.


==== Mail ====
== IPv6 ==
* check the option of '''Mail Routing: I have mail server with another name and would like to add MX hostname...'''
* [https://en.wikipedia.org/wiki/IPv6_subnetting_reference IPv6]
* In 'MX hostname' entering '''aspmx.l.google.com'''
* [https://www.linux.com/learn/intro-to-linux/2017/11/testing-ipv6-networking-kvm-part-1 Testing IPv6 Networking in KVM: Part 1]
* In 'Primary' choose 'Yes, use it as my primary mail relay.'
* [https://www.cloudsavvyit.com/3864/should-you-care-about-ipv6-connectivity-for-your-web-server/ Should You Care About IPv6 Connectivity For Your Web Server?]


After that, see http://yaui.me/postfix-gmail-smtp-server-relay-ubuntu/ for setup on Ubuntu machine.
= ping command =
ping uses the '''ICMP''' Echo Message to force a remote host to echo a packet back to the local host. If packets can travel to and from a remote host, it indicates that the two hosts can successfully communicate.


=== no-ip ===
== Check if a server is up/down if pining to that machine is not allowed ==
Similar to Dyndns. It has its own client program. Needs to build it yourself.
Hint: use nmap to scan open ports
<pre>
nmap -PS22 -p22 <hostname> # port 22 only
# OR
nc -z -v <hostname> 22
</pre>


Also see the [http://support.no-ip.com/customer/portal/articles/375955-basic-troubleshooting-guide troubleshooting guide].
[https://stackoverflow.com/a/34358304 Shell script to check whether a server is reachable?]. I found if a server is up and I am trying a closed port, it will take about 2 minutes before it returns.
<pre>
if nc -z $server 22 2>/dev/null; then
    echo "$server ✓"
else
    echo "$server ✗"
fi
</pre>


See http://ducky-pond.com/posts/12 for instruction of setting autostart on Debian system.
[https://www.2daygeek.com/linux-command-check-website-is-up-down-alive/ 6 Methods to Quickly Check if a '''Website''' is up or down from the Linux Terminal]


See http://www.coulterfamily.org.uk/pages/PCs/Linux/FAQ-LINUX-NO-IP-CLIENT.php for another approach.
== Check if Sites are Online using a PHP script ==
[https://www.makeuseof.com/how-to-use-crontab-linux/ How to Use Crontab to Automate Repetitive Tasks in Linux]


Note: If noip2 cannot start automatically or noip2 does not update even it can be seen from ps -ef command, use '''sudo crontab -e''' command. <span style="color: red"> For some reason, after I use sudo crontab, noip2 can update IP.</span> So the only problem right now is it cannot update every 30 minutes even '''sudo noip2 -S''' says so. The problems may be 1. ps -ef shows the command runs from nobody user 2. sudo noip2 -S says it updates every 30 minutes via /dev/eth0 with NAT enabled.
= Build a home network =
* [https://www.youtube.com/watch?v=dhLKwzVIRzI&index=1&list=PL1l78n6W8zyr-wZWJzRppQUjz6gc_EWzt Virtual router] using vSphere. (Good ! It includes an introduction to vSphere installation)
* http://rbgeek.wordpress.com/2012/05/14/ubuntu-as-a-firewallgateway-router/


Update: An alternative is to use ddclient. However, ddclient never updates the IP.
== IP Subnet Calculator ==
https://www.dan.me.uk/ipsubnets?ip=10.0.0.0


==== Mail ====
* CIDR block    IP range (network - broadcast)    Subnet Mask    IP Quantity 
* Allow only one MX record for each host for free no-ip account.
* 10.0.0.0/24    10.0.0.0 - 10.0.0.255    255.255.255.0  256
* Click Host/Redirects > Manage Hosts > Modify.
* 10.0.0.0/16    10.0.0.0 - 10.0.255.255    255.255.0.0    65536=256^2 
* 10.0.0.0/8    10.0.0.0 - 10.255.255.255    255.0.0.0  16777216=256^3


=== webmin ===
= How Use Your Router and ISP’s Modem/Router Combo In Tandem =
See http://www.webmin.com/deb.html
http://www.howtogeek.com/255206/how-use-your-router-and-isps-modemrouter-combo-in-tandem/
<pre>
wget http://prdownloads.sourceforge.net/webadmin/webmin_1.600_all.deb
dpkg --install webmin_1.600_all.deb
</pre>
The install will be done automatically to ''/usr/share/webmin'', the administration username set to ''root'' and the password to your current root password. You should now be able to login to Webmin at the URL http://localhost:10000/. Or if accessing it remotely, replace localhost with your system's IP address.


=== Virtualize Linux ===
= Troubleshoot and repair network problems =
http://www.linuxuser.co.uk/features/how-to-virtualise-linux-part-1
http://www.linuxuser.co.uk/features/troubleshot-repair-linux-networks


==== Virtualbox ====
== Computer 1 can ping Computer 2 but not reverse ==
See [[Virtualbox|here]].
Use the [[#route|route]] command to solve. See also [http://serverfault.com/questions/391954/linux-router-ping-doesnt-route-back this post].


=== Remote desktop ===
= Simple Network Management Protocol (snmp) =
==== Remote desktop connection from Windows 7 ====
* https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol
xtightvncserver may not play well in Unity.  
* Default port number is 161
* [https://linoxide.com/how-tos/snmp-installation-linux-server/ What Is SNMP? How To Install & Configure SNMP in Linux]
* [http://www.it-slav.net/blogs/2009/02/05/install-and-configure-snmp-on-ubuntu/ Install and configure SNMP on Ubuntu]
* [https://www.dell.com/community/PowerEdge-Hardware-General/Where-to-configure-SNMP-on-iDrac-8/td-p/4585475 Change port number on Dell iDrac 8]
* [https://routersecurity.org/testrouter.php DDoS attack]


Install xrdp on Ubuntu. That's it. See
= Monitor network by Cacti (GUI) =
* http://www.ubuntututorials.com/remote-desktop-ubuntu-12-04-windows-7/ Ubuntu 12.04
* http://www.ubuntugeek.com/install-cacti-monitoring-tool-on-ubuntu-15-10-server.html
* http://www.tweaking4all.com/software/linux-software/use-xrdp-remote-access-ubuntu-14-04/ Ubuntu 14.04
* http://www.cacti.net/
* https://community.hpcloud.com/article/using-windows-rdp-access-your-ubuntu-instance
* http://www.ubuntugeek.com/xrdp-remote-desktop-protocol-rdp-server.html


<pre>
= Monitor network by command line =
sudo apt-get install xrdp
[https://www.linux.com/learn/intro-to-linux/2017/10/3-simple-excellent-linux-network-monitors 3 Simple, Excellent Linux Network Monitors]: iftop, nethogs and vnstat.
sudo /etc/init.d/xrdp start
</pre>


On Windows 7, open its Remote Desktop client utility '''mstsc.exe'''.
== bandwidth ==
[https://www.linuxuprising.com/2020/01/bandwhich-shows-whats-taking-up-your.html bandwhich] Shows What`s Taking Up Your Network Bandwidth On Linux And macOS


==== Remote desktop connection to Windows 7 from xubuntu ====
== iftop ==
<pre>
Use the interface top '''[http://www.ex-parrot.com/pdw/iftop/ iftop]''' command. On ubuntu, we need to use '''sudo apt-get install iftop''' and then run it by '''sudo iftop -i eth0'''.
sudo apt-get update
After that, we can press some keys to toggle options.
sudo apt-get install rdesktop
* p: port
rdesktop xxx.xxx.x.x -f -u USERNAME -p PASSWORD
* s: source
rdesktop 192.168.1.4 -g 1280x720 -u USERNAME -p PASSWORD
* d: destination
</pre>
where '''-f''' option means full screen and '''-g''' means geometry.


==== Remote desktop connection to NCI ====
See [http://www.thegeekstuff.com/2008/12/iftop-guide-display-network-interface-bandwidth-usage-on-linux/ thegeekstuff].
Note that the version 1.7.1 of rdesktop program in Ubuntu 14 has a bug with mouse cursor (invisible). To fix the bug, download the version 1.8.3 and build it. See http://ubuntuforums.org/showthread.php?t=2266743
 
<syntaxhighlight lang='bash'>
sudo apt-get update
sudo apt-get install build-essential libx11-dev libssl-dev libgssglue-dev libpcsclite-dev
tar zxvf rdesktop-1.8.3.tar.gz
cd rdesktop-1.8.3
./configure
make
sudo make install
</syntaxhighlight>
After that the new rdesktop is located under '''/usr/local/bin''' folder. The old rdesktop installed through apt-get is not deleted.


ts.nci.nih.gov:1494
It is strange that the output shows other devices names in my network.


DOMAIN: NIH
<pre>
 
$ dig A pandora.com
resolution: 1024 x 768
$ ipcalc -b 208.85.40.20
$ sudo iftop -F 208.85.40.20/24 -i wlan0
</pre>


Use remmina or rdesktop or freerdp (sudo apt-get install freerdp-x11)
== nethogs ==
<pre>
<pre>
rdesktop ts.nci.nih.gov:1494 -d NIH -u XXXXX -g 1024x768
$ sudo nethogs wlan0
</pre>
</pre>
[https://askubuntu.com/q/1131621 Why does the snapd service use so much data?]


To share a folder from the local machine, use "-r" option
== nload ==
<pre>
<pre>
rdesktop ts.nci.nih.gov:1494 -d NIH -u XXXXX -g 1280x1024 -r disk:remotedisk=/home/$USER/Downloads
nload -m
</pre>
</pre>


The new secure connection relies on the SmartCard is using ncits-p111.nci.nih.gov.
[https://www.tecmint.com/nload-monitor-linux-network-traffic-bandwidth-usage/ nload – Monitor Linux Network Bandwidth Usage in Real Time]


==== Remote desktop connection to Ubuntu ====
The result is the same as [[#gtop_command|gtop]] (gtop is cooler) gives.
* https://www.howtoforge.com/tutorial/x2go-server-ubuntu-14-04/ (X2Go)
* https://community.hpcloud.com/article/using-windows-rdp-access-your-ubuntu-instance
* http://www.ubuntulinuxguide.com/ubuntu-1204-lts/remote-desktop-12-04-lts/
* https://www.howtoforge.com/how-to-install-vnc-server-on-ubuntu-14.04
* https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-vnc-on-ubuntu-14-04
* https://www.linode.com/docs/applications/remote-desktop/using-vnc-to-operate-a-desktop-on-ubuntu-12-04


Network -> Remmina. Protocol: VNC-virtual network. Input IP, username and password.
== bmon ==
https://www.tecmint.com/bmon-network-bandwidth-monitoring-debugging-linux/


==== Allow for remote desktop connection ====
== [http://humdi.net/vnstat/ vnstat] for network traffic monitor ==
# Go to System -> Preference -> Remote desktop. Allow other uses to view your desktop & uncheck you must confirm each access & require user to enter this password.
* [https://www.cyberciti.biz/faq/ubuntu-install-vnstat-console-network-traffic-monitor/ Ubuntu install vnstat console network traffic monitor]
# Go to System -> Preference -> Monitor. Change monitor resolution to 1280 x 720.
* [http://www.thegeekstuff.com/2011/11/vnstat-network-traffic-monitor/ How to Monitor and Log Network Traffic on Linux Using vnStat]
* [https://www.cloudsavvyit.com/5137/how-to-monitor-monthly-bandwidth-usage-in-linux/ How to Monitor Monthly Bandwidth Usage in Linux]


==== Allow for remote desktop connection when vino failed ====
{{Pre}}
* [http://www.teamviewer.com/en/index.aspx Teamviewer]. It works fine. After launching it, the software automatically creates an ID and password. We can change the password so it is fixed. Then launch the software on the client. Use the partner's ID and password to connect to it.
# 1. Install vnStat
sudo apt-get install vnstat


* [https://www.nomachine.com/ NoMachine]. I ran the service on my Ubuntu 12.04 server. I also tested the client on my Android 6.0 tablet and Odroid xu4 running Ubuntu 15.10. I am using the version 5.0.63. I need to use my server's user account info to connect.
# 2. Pick a Interface to Monitor using vnStat
<syntaxhighlight lang='bash'>
vnstat -u -i eth0
odroid@odroid:~/Downloads$ ps -ef | grep nx
vnstat --iflist
nx      12168    1  1 21:11 ?        00:00:20 /usr/NX/bin/nxserver.bin root 12151 --daemon
vnstatd -d # start the daemon
odroid  12199 12168  1 21:11 ?        00:00:12 /usr/NX/bin/nxnode.bin
ps -ef | grep vnst
nx      12225 12168  0 21:11 ?        00:00:00 /usr/NX/bin/nxd
odroid  12263 12199  1 21:11 ?        00:00:13 /usr/NX/bin/nxclient.bin --monitor --pid 1153
nx      15916 12225 24 21:28 ?        00:00:08 /usr/NX/bin/nxserver.bin -c /etc/NX/nxserver --login -H 5
odroid  15944 15916 33 21:29 ?        00:00:04 /usr/NX/bin/nxnode.bin -H 5
odroid  16130  8527  0 21:29 pts/1    00:00:00 grep --color=auto nx


odroid@odroid:~/Downloads$ ls /usr/NX/bin
# 3. vnStat Basic Usage
drivers      nxd        nxkb        nxplayer      nxsh        nxusbd
vnstat
nxagent      nxesd      nxkeygen    nxplayer.bin  nxspool
nxauth        nxexec      nxlocate    nxpost        nxssh
nxclient      nxfs        nxlpd      nxprint      nxssh-add
nxclient.bin  nxfsm      nxnode      nxserver      nxssh-agent
nxcodec.bin  nxfsserver  nxnode.bin  nxserver.bin  nxtunctl
</syntaxhighlight>
If for some reason some nx programs disappeared, restart the service by
<syntaxhighlight lang='bash'>
sudo /usr/NX/bin/nxserver --restart
</syntaxhighlight>


It is interesting that nomachine is faster than 'ssh -X' method when I tested running a Qt application launched from Qt Creator. For example, the progress bar is not moving when it is supposed to move forward and backward when the app is launched through 'ssh -X'.
# 4. vnStat hours, days, months, weeks Network Data
vnstat -d
vnstat -m


==== Remote desktop connection through vmware workstation ====
# 5. Export the data to Excel or other DB
We shall be able to remote desktop connect to a Windows guest machine if the guest machine has configured to use bridge connection and a static IP. If there is a problem, it is likely caused by Window's firewall. See the two screenshots. We can just turn off the firewall of home network but keep the firewall on for the public network.
vnstat --dumpdb


We don't need to use port forward for the remote desktop connection.
# 6. Display Live Network Statistics
vnstat -l


[[File:ViewActiveNetwork.png|100px]]
# 7. Change the default vnstat output format
[[File:Firewall.png|100px]]
vnstat -s (--short)
vnstat --style 0


=== Instal sshd ===
# 8. Display Top 10 Traffic Days
<pre>
vnstat --top10
apt-get update
apt-get install openssh-server
</pre>
</pre>


=== Install LAMP ===
= Network related linux commands =
See the page [http://library.linode.com/lamp-guides/debian-6-squeeze]
* [https://wiki.linuxfoundation.org/networking/net-tools package includes net-tools programs] arp, hostname, ifconfig, ipmaddr, iptunnel, mii-tool, nameif, netstat, plipconfig, rarp, route and slattach. Many of them are obsoleted by the '''ip''' program.
<pre>
* [https://www.makeuseof.com/best-networking-tools-replace-old-net-tools-linux/ The 7 Best Networking Tools That Replace the Deprecated net-tools on Linux] 2022
apt-get install apache2
a2enmod rewrite
apt-get install mysql-server  [I choose branch name as MYSQL root password]
apt-get install php5 php-pear php5-suhosin
apt-get install php5-mysql
/etc/init.d/apache2 restart
</pre>


Another instruction including how to set up user directories for Apache web server http://wiki.debian.org/LaMp
== nmcli and nmtui (useful for getting DNS IPs) ==
* [https://www.cyberciti.biz/faq/how-to-add-network-bridge-with-nmcli-networkmanager-on-linux/ How to add network bridge with nmcli (NetworkManager) on Linux]
* [https://www.tecmint.com/configure-network-connections-using-nmcli-tool-in-linux/ How to Configure and Manage Network Connections Using ‘nmcli’ Tool]
* [https://www.2daygeek.com/enable-disable-up-down-nic-network-interface-port-linux-using-ifconfig-ifdown-ifup-ip-nmcli-nmtui/ How To Enable (UP) And Disable (DOWN) A Network Interface Port (NIC) In Linux?]
* [https://opensource.com/article/20/7/nmcli Manage network connections from the Linux command line with nmcli]
* Wifi
<ul>
<li> [https://kifarunix.com/connect-to-wifi-in-linux-using-nmcli-command/ Connect to WiFi in Linux Using NMCLI command]
<pre>
<pre>
apt-get install mysql-server mysql-client
nmcli radio wifi on
mysql_secure_installation
nmcli dev status
apt-get install apache2 apache2-doc
apt-get install php5 php5-mysql libapache2-mod-php5
apt-get install python libapache2-mod-python
</pre>


The apache configuration file is in '''/etc/apache2/apache2.conf'''.
nmcli dev wifi list # Show signal/bar/rate
sudo nmcli dev wifi rescan


For PHP, it is also useful to install php for command line.
sudo nmcli --ask dev wifi connect MySSID
<pre>
sudo aptitude install php5-cli
</pre>
</pre>
<li>[https://www.tecmint.com/nmcli-connect-wi-fi-from-linux-terminal/ How to Connect Wi-Fi from Linux Terminal Using Nmcli Command]
{{Pre}}
# Find the up network adaptors
$ nmcli dev status
DEVICE          TYPE      STATE        CONNECTION       
docker0          bridge    connected    docker0           
eno1            ethernet  connected    Wired connection 1


Restarting apache before testing on web browser
# Find the DNS
<pre>
$ nmcli dev show | grep 'IP4.DNS'
/etc/init.d/apache2 restart
</pre>
</pre>
</ul>


=== [http://www.ampps.com/downloads AMPPS] for a local server ===
== iwconfig ==
http://www.howtogeek.com/219983/how-to-use-ampps-to-install-joomla-locally/
[https://www.cyberciti.biz/tips/linux-find-out-wireless-network-speed-signal-strength.html 8 Linux Commands: To Find Out Wireless Network Speed, Signal Strength And Other Information]
 
XAMPP is a free, open source cross platform web server solution stack package for Windows, Mac, and Linux. AMPPS is a software stack from Softaculous enabling Apache, MySQL, MongoDB, PHP, Perl, Python, and Softaculous auto-installer on a desktop.
 
=== Install mediawiki using tar ball ===
http://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Ubuntu


=== Install mediawiki using aptitude ===
Getting information ('''Link Quality''', '''Signal level''') about the wireless.
And also the link http://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_GNU/Linux
<pre>
<pre>
aptitude install mediawiki php5 apache2 mediawiki-extensions libapache2-mod-php5
sudo iwconfig
</pre>
</pre>
This will install latex. After the end, we can use Synaptic package manager to see what were installed. Now following the instruction in https://help.ubuntu.com/community/MediaWiki, we remove the '#' from the third line so that it reads 'Alias /mediawiki /var/lib/mediawiki':
 
See link quality continuously on screen
<pre>
<pre>
sudo nano /etc/mediawiki/apache.conf
watch -n 1 cat /proc/net/wireless
sudo /etc/init.d/apache2 restart
</pre>
</pre>
Now we can start mediawiki by opening a browser and pointing it to http://localhost/mediawiki.


We need to enter
== (GUI) NetworkManager ==
<pre>
ps -ef | grep NetworkManager
Site config
  admin username: WikiSysop
  password:


Database config
== ifconfig - spoof the hardware address at the software level ==
  Database name: wikidb
To change the MAC address temporarily on a '''NIC''' (network interface controller),
  DB username:  
{{Pre}}
  DB password:  
sudo ifconfig eth0 down
  Superuser name: root
sudo ifconfig eth0 hw ether 00:11:22:33:44:55
  Superuser password: [depend on how it was chosen when installing MYSQL]
sudo ifconfig eth0 up
</pre>
</pre>
Press the button of "Installing mediawiki". We will be welcomed to the wiki page. Following the instruction,
And it seems there is no need to modify /etc/network/interfaces.


For security reason, I remove new account creation and anonymous editing. I also remove edit counters.
For wlan
{{Pre}}
sudo ifconfig wlan0 down
sudo ifconfig wlan0 hw ether 00:11:22:33:44:55
sudo ifconfig wlan0 up
</pre>


==== Backup and Restore mediawiki ====
See
See docs.google.com note. The process involves 3 parts: mediawiki system, mysql and images.
* [http://www.thegeekstuff.com/2009/03/ifconfig-7-examples-to-configure-network-interface 7 Examples To Configure Network Interface]
* [http://www.tecmint.com/ifconfig-command-examples/ 15 Useful “ifconfig” Commands to Configure Network Interface in Linux]
* [https://serverfault.com/questions/106647/what-does-ifconfig-promisc-mode-do-or-promiscuous-mode-in-general What does ifconfig promisc mode do, or promiscuous mode in general?]


=== Install moinmoin ===
== ip command ==
* Comparison of mediawiki vs moinmoin http://www.wikimatrix.org/compare/MediaWiki+MoinMoin
It is said [http://www.cyberciti.biz/faq/linux-ip-command-examples-usage-syntax/ '''ip''' is replacing the old '''ifconfig''' command on modern Linux distributions].
* Comparison of wiki software http://en.wikipedia.org/wiki/Comparison_of_wiki_software
* Moinmoin website http://moinmo.in/
* moinmoin was used by [http://wiki.fhcrc.org/bioc/HowTo Bioconductor], [https://wiki.ubuntu.com/MoinMoin ubuntu], etc.


=== UpnP server ===
[https://www.cyberciti.biz/faq/linux-ip-command-examples-usage-syntax/# Linux ip Command Examples]
http://bbrks.me/rpi-minidlna-media-server/


It works even I use my phone to tether data (I don't need to turn on wifi on my phone).
http://www.makeuseof.com/tag/networking-commands-linux-terminal/
{{Pre}}
ip a
ip addr
ip address show


<syntaxhighlight lang='bash'>
ip link set DEVICE down # eg ip link set eth0 down
sudo apt-get update
sudo apt-get install minidlna
sudo nano /etc/minidlna.conf # the default location of media files is on /var/lib/minidlna


# rebuild the database. See the comments in <etc/minidlna.conf>
ip link set DEVICE up
sudo service minidlna force-reload
</pre>
sudo service minidlna start
sudo update-rc.d minidlna defaults # ask minidlna to start up automatically upon boot.
</syntaxhighlight>


Too bad is when I played certain videos the program crashed. The /var/log/syslog showed ''kernel: [96495.690373] minidlna[1627]: segfault at 0 ip 00007f4af2de9964 sp 00007fffa43014f8 error 4 in libc-2.15.so[7f4af2d54000+1b4000]''. Also the minidlna process becomes 2 instead of 1 after the crash.
== iptables ==
* See the [[#ufw_.28uncomplicated_firewall.29|ufw]] command which provides an easy way to configure iptables.
* [https://kerneltalks.com/howto/how-to-disable-iptables-firewall-temporarily/ How to disable iptables firewall temporarily]


=== Storage server GlusterFS ===
== route ==
https://www.howtoforge.com/tutorial/high-availability-storage-with-glusterfs-on-debian-8-with-two-nodes/
[http://www.thegeekstuff.com/2012/04/route-examples/ 7 Linux Route Command Examples]


=== Fail2Ban, Tinyhoneypot and IPv4 security ===
# Display Existing Routes ('''route -n''')
https://www.howtoforge.com/tutorial/increase-ipv4-security-with-fail2ban-and-tinyhoneypot-on-debian-jessie/
# Adding a Default Gateway ('''route add default gw 192.168.1.1''')
# List Kernel’s Routing Cache Information ('''route -Cn''')
# Reject Routing to a Particular Host or Network ('''route add -host 192.168.1.51 reject''')
# Make 192.168.3.* Accessible from 192.168.1.* ('''route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.3.10''')
# Make 192.168.1.* Accessible from 192.168.3.* ('''route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.10''')
# Allow Internet Access/External World ('''route add default gw 125.250.60.59''')


=== MYSQL security ===
On Ubuntu 16.04, it shows
Just execute '''mysql_secure_installation''' from the command line.
{{Pre}}
$ route
Kernel IP routing table
Destination    Gateway        Genmask        Flags Metric Ref    Use Iface
default        FIOS_Quantum_Ga 0.0.0.0        UG    600    0        0 wlp3s0
link-local      *              255.255.0.0    U    1000  0        0 wlp3s0
192.168.1.0    *              255.255.255.0  U    600    0        0 wlp3s0
$ route -n  # showing numerical IP address instead of host name.
Kernel IP routing table
Destination    Gateway        Genmask        Flags Metric Ref    Use Iface
0.0.0.0        192.168.1.1    0.0.0.0        UG    600    0        0 wlp3s0
169.254.0.0    0.0.0.0        255.255.0.0    U    1000  0        0 wlp3s0
192.168.1.0    0.0.0.0        255.255.255.0  U    600    0        0 wlp3s0
</pre>
Flag value 'U' means ''up'' and 'G' means ''gateway'.


* You can set a password for root accounts.
== Connect two networks ==
* You can remove root accounts that are accessible from outside the local host.
The trick is explained in [http://unix.stackexchange.com/questions/68418/how-to-add-two-gateway-on-same-machine this post] or the above '''route''' command.
* You can remove anonymous-user accounts.
* You can remove the test database, which by default can be accessed by anonymous users.


See http://www.mysql-optimization.com/mysql-secure-installation-program.html
For example, my network structure is
* Modem/router: LAN IP 192.168.1.*/24
* PC1: connect to Modem/router
* Second router (ASUS) connect to Modem/router: its WAN IP is 192.168.1.ASUS. It's LAN IP 192.168.2.*/24
* PC2 (raspberry pi): connect to the second router (ASUS): its IP is 192.168.1.212


=== Compiling R ===
By default, PC2 can ssh to PC1 but PC1 cannot access PC2.
Use the following command to download required components before building any R packages. See also [http://cran.r-project.org/bin/linux/ubuntu/ ubuntu package for R]
 
<pre>
The following command will solve the problem that PC1 cannot access PC2:
sudo apt-get build-dep r-base
{{Pre}}
# From PC1
$ sudo route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.1.ASUS
$ ssh [email protected]    # 192.168.2.212 is the IP address for the Raspberry Pi
 
$ netstat -rn
Kernel IP routing table
Destination    Gateway        Genmask        Flags  MSS Window  irtt Iface
0.0.0.0        192.168.1.1    0.0.0.0        UG        0 0          0 eth0
192.168.1.0    0.0.0.0        255.255.255.0  U        0 0          0 eth0
192.168.2.0    192.168.1.ASUS  255.255.255.0  UG        0 0          0 eth0
</pre>
</pre>


=== PPA management ===
[https://www.linux.com/learn/intro-to-linux/2018/3/linux-lan-routing-beginners-part-2 One article] from linux.com using the '''ip''' command.
* https://www.howtoforge.com/tutorial/ubuntu-ppa-management/


=== Create .deb file ===
== traceroute ==
'''[https://help.ubuntu.com/community/CheckInstall checkinstall]''' command
{{Pre}}
* http://community.linuxmint.com/tutorial/view/162
sudo apt-get install traceroute
* http://www.linuxjournal.com/content/using-checkinstall-build-packages-source
traceroute 8.8.8.8
* https://www.linux.com/learn/tutorials/307110-easy-package-creation-with-checkinstall
</pre>
* http://www.linuxuser.co.uk/tutorials/build-your-own-deb-and-rpm-packages


'''[https://debian-handbook.info/browse/stable/debian-packaging.html dpkg-buildpackage]''' command  
On Windows, we can use the '''tracert''' command. For example, '''tracert www.microsoft.com'''.
* http://conoroneill.net/controlling-an-i-racer-rc-car-using-a-wii-balance-board-and-raspberry_pi/
 
=== Package repository and /etc/apt/sources.list ===
* https://help.ubuntu.com/community/Repositories/CommandLine
* http://askubuntu.com/questions/197564/how-do-i-add-a-line-to-my-etc-apt-sources-list
<syntaxhighlight lang='bash'>
echo "new line of text" | sudo tee -a /etc/apt/sources.list
# OR
# use 'add-apt-repository' command
sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 886DDD89
sudo add-apt-repository "deb http://deb.torproject.org/torproject.org $(lsb_release -s -c) main"
sudo apt-get update
</syntaxhighlight>


* https://www.digitalocean.com/community/tutorials/how-to-set-up-r-on-ubuntu-14-04
== nslookup (convert between hostname and ip) and host ==
<syntaxhighlight lang='bash'>
* https://en.wikipedia.org/wiki/Nslookup
sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu trusty/" >> /etc/apt/sources.list'
* https://en.wikipedia.org/wiki/Host_(Unix)
# Or the following if the OS is Ubuntu
* [https://stackoverflow.com/a/24196970 How to get hostname from IP (Linux)?]
# (other derived distributions like Linux Mint do not count)
# because $(lsb_release -s -c) returns the CodeName which diffs from each Linux distributions.
# sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu $(lsb_release -s -c)/" >> /etc/apt/sources.list'


gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9
{{Pre}}
gpg -a --export E084DAB9 | sudo apt-key add -
$ host google.com
sudo apt-get update
google.com has address 172.217.5.238
sudo apt-get -y install r-base
google.com has IPv6 address 2607:f8b0:4004:802::200e
</syntaxhighlight>
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.


=== Package maintenance ===
$ nslookup google.com
* https://help.ubuntu.com/community/AptGet/Howto#Maintenance_commands
Server:         127.0.1.1
* [http://www.tecmint.com/useful-basic-commands-of-apt-get-and-apt-cache-for-package-management/ 25 Useful Basic Commands of APT-GET and APT-CACHE for Package Management]
Address:       127.0.1.1#53


==== List all available packages (from repositories) ====
Non-authoritative answer:
Name:  google.com
Address: 172.217.7.238
</pre>
<pre>
<pre>
apt-cache pkgnames
mac$ nslookup cran.r-project.org
</pre>
Server: 156.40.70.10
Address: 156.40.70.10#53
 
Non-authoritative answer:
cran.r-project.org canonical name = cran.wu-wien.ac.at.
Name: cran.wu-wien.ac.at
Address: 137.208.57.37


==== Upgrade a package ====
mac$ nslookup 137.208.57.37
apt-get install <package_name>
Server: 156.40.70.10
Address: 156.40.70.10#53


==== Install specific version of the package ====
Non-authoritative answer:
Use the "=" with the package-name and append desired version.
37.57.208.137.in-addr.arpa name = cran.wu-wien.ac.at.
<pre>
sudo apt-get install vsftpd=2.3.5-3ubuntu1
</pre>
</pre>


==== Remove a package ====
The first two lines show the IP address of my DNS. If we run the command inside a Docker container where DNS was specified manually, the IP address we specified will be shown here.
<pre>
sudo apt-get remove <package_name>
</pre>


To completely remove a package including their configuration files
== dig ==
<pre>
[https://toolbox.googleapps.com/apps/dig/ Dig] provided by Google G Suite Toolbox. If the office internet is interrupted, we can use a cell phone to search for the IP address of a website for trouble shooting.
sudo apt-get purge <package_name>
sudo apt-get remove --purge <package_name>
</pre>


==== Rollback an apt-get upgrade ====
{{Pre}}
http://www.cyberciti.biz/howto/debian-linux/ubuntu-linux-rollback-an-apt-get-upgrade/
$ sudo apt-get install dnsutils
$ dig world.std.com
; <<>> DiG 9.9.5-3ubuntu0.16-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49227
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1


==== Clean up disk space ====
;; OPT PSEUDOSECTION:
The clean command is used to free up the disk space by cleaning retrieved .deb files from the local repository.
; EDNS: version: 0, flags:; udp: 512
<pre>
;; QUESTION SECTION:
sudo apt-get clean
;google.com.                   IN      A
</pre>


==== Auto clean up apt-get cache ====
;; ANSWER SECTION:
<pre>
google.com.            130    IN      A      172.217.5.238
sudo apt-get autoclean
</pre>
The 'autoclean' command deletes all .deb files from '''/var/cache/apt/archives''' to free up disk space.


==== Download only source code of package ====
;; Query time: 11 msec
<pre>
;; SERVER: 127.0.1.1#53(127.0.1.1)
sudo apt-get --download-only source <package_name>
;; WHEN: Fri Dec 01 17:32:37 EST 2017
;; MSG SIZE  rcvd: 55
</pre>
</pre>


To download and unpack source code of a package
== arp (Address Resolution Protocol) ==
<pre>
The '''arp ''' command can be used to show the MAC addresss of all hosts in LAN
sudo apt-get source <package_name>
{{Pre}}
arp -a
</pre>
</pre>


To download, unpack and compile a package
== Check connectivity ==
[https://twitter.com/droy_eclipse/status/1456286541005852682?s=20 Using bash tcp built-ins to test connectivity] when nothing else is available:
<pre>
<pre>
sudo apt-get --compile source <package_name>
echo >/dev/tcp/google.com/80;
if [ $? -eq 0 ]; then echo "Connection Successful"; fi
</pre>
</pre>


==== Download without installing ====
= Find open ports =
<pre>
sudo apt-get download <package_name>
</pre>


==== Check change log of package ====
{| class="wikitable"
Note that the change log may not be found.
! command
<pre>
! example
sudo apt-get changelog <package_name>
! comment
</pre>
|-
| ss
| sudo ss -tulpn &#124; grep LISTEN
| contain '''pid''', <br />
add "sudo" can show program/command names on the last column, <br />
''' ''Even DietPi includes the ss command'' '''
|-
| lsof
| sudo lsof -i -P -n &#124; egrep "PID&#124;LISTEN"
| '''sudo''' is required. Contain pid. Using '''egrep''' to include header in output. It includes the command/program names on the first column. <br />
lsof may not be available by default in many OS.
|-
| '''nmap''' (network mapper)
| nmap localhost (OR IP)
| '''shortest output and input'''. Need to install. No 'sudo' needed. Works on non local.
|-
| netstat <br />
(old '' 'net-tools' '')
| netstat -tlpn &#124; grep LISTEN &#124; awk '{print $4 "\t" $7}'
| show pid and program name. Need to install netstat. '''Windows already has it'''.
|-
| nc
| nc -zvw3 <hostname> <port>
| need to specify a port number. More accurate than '''nmap'''. "-w3" means time out after 3 seconds.
|}
 
== What are network interface ports ==
[https://www.howtoforge.com/understanding-network-interface-ports-in-linux Understanding Network Interface Ports in Linux]. In networking, the term "port" can refer to different concepts depending on the context:
* Hardware Ports:
* Software Ports: These are '''virtual endpoints''' in an operating system used by '''network protocols''' to manage '''connections'''. Software ports are identified by a number, ranging from 0 to 65535. For example, port 80 is used for HTTP, and port 443 is used for HTTPS.
 
== Socket ==
[https://www.cloudsavvyit.com/1263/what-are-unix-sockets-and-how-do-they-work/ What Are Unix Sockets and How Do They Work]
 
== nmap/network mapper - port scanning & IPs in local network ==
[https://en.wikipedia.org/wiki/Nmap nmap] - Network exploration tool and security / port scanner
<ul>
<li>[https://stackoverflow.com/a/30746873 nmap does not show all open ports] By default, Nmap scans [https://nmap.org/book/man-port-specification.html the most common 1,000 ports] for each protocol. </li>
<li>https://nmap.org/book/nmap-os-db.html. Local OS database is located at '''/usr/share/nmap/nmap-os-db'''. The 2nd line will show the revision number.
<ul>
<li>Modifying the nmap-os-db Database Yourself </li>
<li>Download the latest from https://svn.nmap.org/nmap/nmap-os-db. Note that the current revision number has to be found from the [https://svn.nmap.org/nmap/ website]. You can edit the file and insert the revision number on the 2nd line of your local copy. </li>
<li>Even I update the database, it cannot detect my Ubuntu 14.04 OS (it only shows OS details: Linux 3.8 - 4.9). For the Raspberry Pi, it can show information from the network adapter; e.g. MAC Address: AA:BB:CC:DD:EE:FF (Raspberry Pi Foundation) but not the OS name (OS details: Linux 3.2 - 4.8).
{{Pre}}
sudo mv /usr/share/nmap/nmap-os-db /usr/share/nmap/nmap-os-db-old


==== Check broken dependencies ====
cd /usr/share/nmap
<pre>
sudo wget https://svn.nmap.org/nmap/nmap-os-db
sudo apt-get check
</pre>
</pre>
</li>
</ul>
</li>
<li>http://www.cyberciti.biz/networking/nmap-command-examples-tutorials/
</li>
<li>http://bencane.com/2013/02/25/10-nmap-commands-every-sysadmin-should-know/
</li>
<li>http://www.tecmint.com/nmap-command-examples/
{{Pre}}
sudo apt-get install nmap


==== Search missing package's full name ====
nmap 192.168.1.100  # does not require root privileges
Use the '''apt-file''' command. See [http://kobablog.wordpress.com/2011/05/17/how-to-find-and-install-the-missing-file-in-ubuntu/ this post]
                    # used to check open ports


At first, install apt-file command and prepare it.
nmap 192.168.1.*    # show IPs and ports in LAN
<syntaxhighlight lang='bash'>
$ sudo apt-get install apt-file
$ sudo apt-file update
</syntaxhighlight>


To find zlib.h,
sudo nmap -sP 192.168.1.1/24 # show connected IPs (no hostnames?) and MAC addresses
<syntaxhighlight lang='bash'>
                            # If you don't use 'sudo' only partial devices can be found
$ apt-file search zlib.h
                            # The output may contains the hostname. For example,
</syntaxhighlight>
                            # Nmap scan report for brb-P45T-A.fios-router.home (192.168.1.xxx)
nmap -sV 192.168.1.1 # show Daemon name (in VERSION column) together with port number


It reports too many result. Let’s narrow down.
nmap -T4 -F 192.168.1.99-255 # show connected IPs and open ports
<syntaxhighlight lang='bash'>
                            # -F means fast
$ apt-file search /usr/include/zlib.h
nmap -F taichimd.us  # Note that domain name != server
zlib1g-dev: /usr/include/zlib.h
nmap -v taichimd.us
</syntaxhighlight>


Now you know zlib.h is in zlib1g-dev package.
nmap -A 192.168.1.1  # Aggressive scan (more output)
<syntaxhighlight lang='bash'>
$ sudo apt-get install zlib1g-dev
</syntaxhighlight>


==== Find package information before installing it ====
nmap -p http,ssh,mysql taichimd.us  # scan ports/services
Use "-s" option for simulation. No sudo is necessary.
                                    # note that mysql will be shown as closed
<pre>
                                    # ssh port is not correct.  
apt-get -s install PACKAGENAME
                                    # Not sure how to get the correct ssh port using nmap
</pre>
nmap --open taichimd.us  # scan open ports
The output is too much (include other dependences)


A better way is to use '''aptitude''' (which is not installed by default in Ubuntu)
sudo nmap -traceroute nih.gov
<pre>
 
aptitude search <package> -F "%c %p %d %V"
sudo nmap -sS -O 192.168.1.99 # -O shows operating system
</pre>
                              # eth0 MAC
For example,
<pre>
debian@beaglebone:~/qt-4.8.5/bin$ aptitude search  qtcreator -F "%c %p %d %V"
p qtcreator                        lightweight integrated development environme 2.5.0-2     
p qtcreator:armel                  lightweight integrated development environme 2.5.0-2     
p qtcreator-dbg                    debugging symbols for Qt Creator IDE        2.5.0-2     
p qtcreator-dbg:armel              debugging symbols for Qt Creator IDE        2.5.0-2     
p qtcreator-doc                    documentation for Qt Creator IDE            2.5.0-
</pre>


If a package is already installed, we can use the following way to check version number.
$ nmap localhost # showing the true ports from the server
<pre>
apt-show-versions <package>
</pre>


==== Show package information ====
Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-09 15:01 EDT
<pre>
Nmap scan report for localhost (127.0.0.1)
apt-cache show <package_name>
Host is up (0.00016s latency).
</pre>
Not shown: 996 closed ports
==== Check dependencies for specific packages ====
PORT    STATE SERVICE
<pre>
22/tcp  open  ssh
apt-cache showpkg <package_name>
25/tcp  open  smtp
</pre>
80/tcp  open  http
631/tcp open  ipp


==== List files in a package ====
$ nmap localhost -p 3838-4000  # Shiny
<pre>
dpkg -L <package_name>
</pre>
==== List racing games package (kind of search packages by key words) ====
<pre>
apt-cache search racing game
apt-cache search vsftpd
</pre>
</pre>
</li>
<li>A gui version of nmap is called '''[https://nmap.org/zenmap/ Zenmap]'''. [https://www.how2shout.com/linux/install-zenmap-nmap-gui-on-ubuntu-20-04-lts-linux/ How to install Zenmap Nmap GUI on Ubuntu 20.04 LTS]</li>
</ul>


==== Search installed packages ====
== netstat: get a list of all open ports ==
<syntaxhighlight lang='bash'>
[https://www.ghacks.net/2018/03/21/how-to-use-netstat-in-gnu-linux/ How to use netstat in GNU/Linux]
dpkg -l libgtk* | grep -e '^i'
dpkg -l libpng* | grep -e '^i'
dpkg -l libjpeg* | grep -e '^i'
</syntaxhighlight>


To search x-org related packages
*    -l or --listening shows only the sockets currently listening for incoming connection.
<syntaxhighlight lang='bash'>
*    -a or --all shows all sockets currently in use.
udooer@udoo:~$ dpkg -l | grep xserver-xorg | awk '{$1=$3=$4=""; print $0}'  # Skip columns 1,3,4
*    -e    --show extended/additional information
imx-xserver-xorg-extension-viv-9t6-hdmi  Freescale Xorg server driver extension for HDMI performance
*    -t or --tcp shows the tcp sockets.
imx-xserver-xorg-video-viv-9t6  Xorg server driver for imx6, vivante
*    -u or --udp shows the udp sockets.
xserver-xorg  X.Org X server
*    -n or --numeric shows the hosts and ports as numbers, instead of resolving in dns and looking in /etc/services.
xserver-xorg-core  Xorg X server - core server
*    -s    --Print network stats
xserver-xorg-dev  Xorg X server - development files
*    -r    --Print the network routing information
xserver-xorg-input-all   X.Org X server -- input driver metapackage
*    -p    --Print PID and name of the program to which each socket belongs
xserver-xorg-input-evdev  X.Org X server -- evdev input driver
xserver-xorg-input-synaptics  Synaptics TouchPad driver for X.Org server
xserver-xorg-input-wacom  X.Org X server -- Wacom input driver
xserver-xorg-video-all  X.Org X server -- output driver metapackage
xserver-xorg-video-fbdev  X.Org X server -- fbdev display driver
xserver-xorg-video-modesetting  X.Org X server -- Generic modesetting driver
xserver-xorg-video-omap  X.Org X server -- OMAP display driver
xserver-xorg-video-vesa  X.Org X server -- VESA display driver
</syntaxhighlight>


==== List of installed packages ====
{{Pre}}
<pre>
netstat -l            # only listening ports
dpkg --get-selections
netstat -rn            # displays the system's routing table
</pre>
netstat -at
Or using [https://wiki.debian.org/ListInstalledPackages dpkg-query] utility.
netstat -ant          # For tcp
<pre>
sudo netstat -pant    # show ports and programs (pant = 喘氣). Best of the best!!!
dpkg-query -l
sudo netstat -peanut  # (output is too wide)
netstat -anp | grep 3306 | wc -l # print # of connections for the port mysql port
</pre>
</pre>


==== Show (sort) package size ====
Other commands
<pre>
{{Pre}}
dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -n
sudo lsof -i -P -n | grep LISTEN
sudo ss -tulpn
sudo netstat -tulpn | grep LISTEN
sudo netstat -tulpn  # include dhcpcd & avahi-daemon
</pre>
</pre>


==== Check if a library is installed or not ====
== ss command ==
Use '''ldconfig -p | grep LIBNAME'''. For example, to check if ''libxml'' is installed or not,
ss is one of [https://www.2daygeek.com/linux-scan-check-open-ports-using-netstat-ss-nmap/ 4 commands to check open ports for Linux]. The 4 commands are '''netstat''', '''nmap''', '''ss''' and '''lsof'''.
<pre>
EXIST=`ldconfig -p | grep libxml | wc -l`
if [ $EXIST -ng 0 ]; then echo EXISTING; fi
</pre>


==== How to uninstall software ====
[https://www.howtogeek.com/681468/how-to-use-the-ss-command-on-linux/ How to Use the ss Command on Linux]
http://www.howtogeek.com/229699/how-to-uninstall-software-using-the-command-line-in-linux/
 
== lsof command ==
[https://www.cloudsavvyit.com/13145/how-to-use-lsof-in-linux-with-a-practical-example/ How to Use lsof in Linux (With a Practical Example]. How to discover what files are currently open and in use on your system?


==== Upgrade software packages ====
Upgrade all the currently installed software packages on the system
<pre>
<pre>
sudo apt-get upgrade
sudo apt install lsof  # dietpi
</pre>


If you want to upgrade, unconcerned of whether software packages will be added or removed to fulfill dependencies, use
# Basic lsof Output
<pre>
sudo su
sudo apt-get dist-upgrade
lsof | head -n10
</pre>


==== List of available (uninstalled) packages ====
lsof -i  # this gives a more list than nmap command
<pre>
aptitude -F "%p" search "?not(?installed)"
</pre>
</pre>
See http://superuser.com/questions/408082/how-do-i-get-a-list-of-available-i-e-uninstalled-packages-in-debian


==== Check Change Log of Package ====
== Common ports ==
http://www.tecmint.com/useful-basic-commands-of-apt-get-and-apt-cache-for-package-management/
* [https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers List of TCP and UDP port numbers]
<pre>
** Well-known ports: 0 to 1023
sudo apt-get changelog PKGNAME
** Registered ports: 1024 to 49151
</pre>
** Dynamic, private or ephemeral ports: 49152–65535
* [https://phoenixnap.com/kb/nmap-scan-open-ports A List of Common Ports]
* Replace the default port (such as 22 for ssh) with anyone from 1024-65535 because ports numbers up to 1023 are “well known” ports & should be avoided
* Some services:
** 81: [https://nginxproxymanager.com/ Nginx Proxy Manager]
** 1194: OpenVPN
** 3306: MYSQL
** 3838: Shiny
** 8000: [https://github.com/portainer/portainer-docs/issues/91 portainer]
** 9000: portainer (URL)
** 9090: cockpit
** 17500, 17600, 17603: [https://help.dropbox.com/installs-integrations/desktop/configuring-firewall Dropbox]


==== Clean up/remove packages ====
= Copy text to a clipboard to be used in other apps =
[http://www.ubuntugeek.com/cleaning-up-a-ubuntu-gnulinux-system-updated-with-ubuntu-14-10-and-more-tools-added.html ubuntugeek.com]
Install the '''xclip''' program. See [http://www.cyberciti.biz/faq/xclip-linux-insert-files-command-output-intoclipboard/ here] or [http://stackoverflow.com/questions/5130968/how-can-i-copy-the-output-of-a-command-directly-into-my-clipboard here].
{{Pre}}
sudo apt-get install xclip
# Examples
sort -n -k 3, -k 2 file.txt | xclip -selection clipboard


==== unmet dependencies after adding a PPA ====
cat ~/.ssh/id_rsa.pub | xclip -sel clip
http://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies-after-adding-a-ppa
</pre>
Works.


= Start Emacs without X =
Add '''-nw''' (no window) option.
<pre>
<pre>
$ sudo apt-get install libgl1-mesa.dev
emacs -nw
Reading package lists... Done
Building dependency tree     
Reading state information... Done
Note, selecting 'libgl1-mesa-dev-lts-quantal' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev-lts-saucy' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev-lts-trusty' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev-lts-utopic' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev-lts-vivid' for regex 'libgl1-mesa.dev'
Note, selecting 'libgl1-mesa-dev-lts-raring' for regex 'libgl1-mesa.dev'
libgl1-mesa-dev is already the newest version.
libgl1-mesa-dev set to manually installed.
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
 
The following packages have unmet dependencies:
libgl1-mesa-dev : Conflicts: libgl-dev
                  Conflicts: libgl1-mesa-dri-dev
libgl1-mesa-dev-lts-utopic : Depends: mesa-common-dev-lts-utopic (= 10.3.2-0ubuntu1~trusty2) but it is not going to be installed
                              Depends: libgl1-mesa-glx-lts-utopic (= 10.3.2-0ubuntu1~trusty2) but it is not going to be installed
                              Conflicts: libgl-dev
                              Conflicts: libgl1-mesa-dev
                              Conflicts: libgl1-mesa-dri-dev
libgl1-mesa-dev-lts-vivid : Depends: mesa-common-dev-lts-vivid (= 10.5.9-2ubuntu1~trusty2) but it is not going to be installed
                            Depends: libgl1-mesa-glx-lts-vivid (= 10.5.9-2ubuntu1~trusty2) but it is not going to be installed
                            Conflicts: libgl-dev
                            Conflicts: libgl1-mesa-dev
                            Conflicts: libgl1-mesa-dri-dev
                            Conflicts: xorg-renamed-package-lts-utopic
E: Unable to correct problems, you have held broken packages.
</pre>
</pre>


=== View logs ===
= Audio =
* Apache /var/log/apache2/access.log
== Record audio from mic ==
[https://lifehacker.com/how-to-save-important-voicemails-for-both-iphone-and-an-1833241417 How to Save Important Voicemails for Both iPhone and Android]. Hint: use Audacity.


=== Torrent ===
== mp3 codecs ==
Popular search sites
https://help.ubuntu.com/community/RestrictedFormats
* torrentz
{{Pre}}
* thepiratebay
sudo apt-get install ubuntu-restricted-extras
* isohunt
</pre>
* kickass torrents


==== How to set up torrent scheduling on Linux ====
== Concatenate mp3 files ==
https://www.howtoforge.com/tutorial/how-to-set-up-torrent-scheduling-on-linux/. It covers 'Deluge', 'Transmission' and 'Rtorrent'. 
{{Pre}}
sudo apt-get install mp3wrap
mp3wrap output.mp3 *.mp3
</pre>


This can be useful for people who want to take advantage of their computer while they are not using it, like during the nighttime for example. This way, large portions of huge files can be downloaded without delaying your work activities, or interrupting/undermining your media consumption.
== Reduce the size of an mp3 file ==
 
Specify a new lower bitrate using the -b option in '''lame'''. For example if your starting mp3 has a quality of 256kbs you can lower its bitrate to 128kbps (or even lower like 64kbps) by:
==== Torrent client command line: [http://aria2.sourceforge.net/ aria2c] ====
{{Pre}}
aria2 is a lightweight multi-protocol & multi-source command-line download utility. It supports '''HTTP/HTTPS, FTP, BitTorrent''' and '''Metalink'''. aria2 can be manipulated via built-in '''JSON-RPC''' and '''XML-RPC''' interfaces.
lame --mp3input -b 128 input.mp3 output.mp3
 
http://linuxconfig.org/aria2-all-in-one-command-line-download-tool
<pre>
sudo apt-get install aria2
aria2c magnet:?xt=urn:btih:1e99d95f1764644a86a8e99bfd80c ...
</pre>
</pre>


==== Torrent client: transmission-cli ====
== Convert ogg to mp3 ==
https://wiki.archlinux.org/index.php/Transmission
'''ffmpeg''' is not included in Ubuntu repository. Use the '''avconv''' command. http://superuser.com/questions/15327/how-to-convert-ogg-to-mp3
 
{{Pre}}
==== Torrent client command line: rtorrent ====
sudo apt-get install libav-tools
We first need to create an .rtorrent.rc file under $HOME directory. Then run
avconv -i input.ogg -c:a libmp3lame -q:a 2 output.mp3
<pre>
rtorrent XXX.torrent
</pre>
</pre>
* https://wiki.archlinux.org/index.php/RTorrent
* http://harbhag.wordpress.com/2010/06/30/tutorial-using-rtorrent-on-linux-like-a-pro/ [download a template]
* http://mylinuxbook.com/rtorrent-bit-torrent-client/


In the simplest case, .rtorrent.rc looks like
== Convert m4a/webm to mp3 ==
<pre>
{{Pre}}
# On the terminal, mkdir ~/Downloads/rsession
avconv -i input.m4a output.mp3
download_rate = 0
upload_rate =50
directory = ~/Downloads
session = ~/Downloads/rsession
port_range = 55556-55560
scgi_port = 127.0.0.1:5000
use_udp_trackers = yes
encryption = allow_incoming,try_outgoing,enable_retry
</pre>
</pre>
As you can see here, I have created a sub-directory ''rsession'' under ~/Downloads/.


[https://wiki.archlinux.org/index.php/RTorrent#Key_bindings Keybinding]:
== Remove the vocals from any song using Audacity ==
* ctrl + q = quit application
https://www.makeuseof.com/tag/remove-vocals-song-audacity/
* ctrl + d = stop an active download
* ctrl + s = start downloading


=== glibc ===
== How to Remove Ambient Noise From Audio Files Using Audacity ==
==== Patch glibc 2.9 ====
[https://www.makeuseof.com/tag/remove-ambient-noise-audio-files-audacity/ How to Remove Ambient Noise From Audio Files Using Audacity]
* http://www.infoworld.com/article/3033862/security/patch-now-unix-bug-puts-linux-android-and-ios-systems-at-risk.html
* http://www.cyberciti.biz/faq/linux-patch-cve-2015-7547-glibc-getaddrinfo-stack-based-buffer-overflow/
<syntaxhighlight lang='bash'>
sudo apt-get update
sudo apt-get upgrade
sudo reboot
</syntaxhighlight>


=== SSL ===
== Normalize the volume of an audio file ==
==== Install commercial SSL certificate ====
* [http://www.howtogeek.com/280739/can-you-losslessly-increase-the-volume-of-mp3-files/ Can You Losslessly Increase the Volume of MP3 Files?]
* https://www.digitalocean.com/community/tutorials/how-to-install-an-ssl-certificate-from-a-commercial-certificate-authority
* Use [http://www.thebest3d.com/audacity/tutorials/make-louder/audacity-tutorial-make-louder-more-volume-increased-amplitude.html Audacity]. To raise (Amplify) volume:
* [https://www.namecheap.com/support/knowledgebase/article.aspx/9423/0/apache-opensslmodssl Installing a SSL certificate on Apache]
*# Edit > Select All.
* https://www.namecheap.com/support/live-chat/ssl.aspx
*# Effect > Amplify. Increase db. Adjust the sound until the highest peaks and lowest valleys of the waveform reach the top and bottom of the window.
* [https://www.digitalocean.com/community/tutorials/how-to-set-up-a-host-name-with-digitalocean How To Set Up a Host Name with DigitalOcean] This includes information about WHOIS, changing domain server, configuring domain (A record, AAAA record, CNAME record, MX record, et al)
*# Check clip3. Export > MP3 or just start to listen.
 
* Command line tool: [https://libav.org/avconv.html avconv] (replace '''ffmpeg''' program). See [http://gfxile.net/z/?p=1343 this post].
==== openssl & patch bug ====
{{Pre}}
* Check out https://launchpad.net/ubuntu/+source/openssl to see the latest openssl version (number may be different for each of Ubuntu version). As of this writing, the latest openssl on Ubuntu 14.04 is 1.0.1f-1ubuntu2.15 and for Ubuntu 12.04 it is 1.0.1-4ubuntu5.31 (this kind of representation can be obtained using the sudo dpkg -l | grep  openssl command; see below). '''The full list of the publishing history can be accessed through [https://launchpad.net/ubuntu/+source/openssl/+publishinghistory View full publishing history link].''' From there, we can restrict to Target = Trusty, for example.
avconv -ss 00:00:10 -i OLD.mp3 -vol 2560 NEW.mp3
* http://askubuntu.com/questions/444702/how-to-patch-the-heartbleed-bug-cve-2014-0160-in-openssl. The following is an output after running ''sudo apt-get update; sudo apt-get upgrade''.
</pre>
<pre>
The anconv/ffmpeg -vol parameter amplifies the sound. The default value is 256 (no amplification), and you can adjust the number accordingly. Here it’s 2560, as it’s 10 times louder. Note that these are not decibel values or anything that sophisticated, but just an integer value. 512 equals to twice the volume, 768 three times, 1024 four times, etc. The -ss parameter specifies the start time offset. Here it will skip the first 10 seconds.
brb@vm-1404:~$ sudo dpkg -l | grep  openssl
* Command line tool: [http://sox.sourceforge.net/ sox].
ii  libgnutls-openssl27:amd64  2.12.23-12ubuntu2.2  amd64        GNU TLS library - OpenSSL wrapper
** http://askubuntu.com/questions/246242/how-to-normalize-sound-in-mp3-files
ii  openssl                    1.0.1f-1ubuntu2.15    amd64        Secure Sockets Layer toolkit - cryptographic utility
** http://www.linuxandlife.com/2013/03/how-to-use-sox-audio-editing.html
ii  python-openssl              0.13-2ubuntu6        amd64        Python 2 wrapper around the OpenSSL library
** http://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/ deal with several kinds of silence.  
** http://www.thegeekstuff.com/2009/05/sound-exchange-sox-15-examples-to-manipulate-audio-files/
I found the converted file by sox has about one half file size compared to anconv/ffmpeg program (source file=47MB, anconv converted=135MB, sox converted file=54MB).
{{Pre}}
sudo apt-get install sox libsox-fmt-all
sox --norm OLD.mp3 NEW.mp3 trim 10
sox --norm OLD.mp3 NEW.mp3 silence 1 0.1 1%
sox -v 4.0 OLD.mp3 NEW.mp3            # increase volume
</pre>
</pre>
* http://www.liquidweb.com/kb/update-and-patch-openssl-on-ubuntu-for-the-ccs-injection-vulnerability/. As you can see although a bug in OpenSSL has been found affecting versions 1.0.1 through 1.0.1f (inclusive), and openssl version is still 1.0.1f in  Ubuntu 14.04.1, the build date is on June 2014. So it is safe.
where '--norm' will normalize the audio and the 'trim' option set to skip the first 10 seconds. The silence parameter allows to trim silence at the beginning without a need to specify the number of seconds.
<pre>
brb@vm-1404:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.1 LTS
Release: 14.04
Codename: trusty


brb@vm-1404:~$ openssl version -a
== cut, delete or trim an audio ==
OpenSSL 1.0.1f 6 Jan 2014
# Open the audio file in audacity.
built on: Fri Jun 20 18:54:02 UTC 2014
# select a region in the '''waveform''' area. Do not select in the time interval area (above the waveform).
platform: debian-amd64
## To precisely select a range from one position to the end. Click Zoom in several times. Click one position in the '''waveform''' and click Edit -> Select -> Cursor to the track end to select
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)  
## Similarly, if we want to precisely select a range from the start to some position, we can click one position in the '''waveform''' and then click Edit -> Select -> Track start to cursor.
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64
## To move around the track, use the scrollbar (below the waveform and above the bottom toolbar, not quite clear in Ubuntu/Unity)
OPENSSLDIR: "/usr/lib/ssl"
# Click Edit -> Remove Audio or labels -> Cut/Delete/Trim Audio
# play the new audio by clicking the green triangle.
# File -> Export -> mp3 format.


brb@vm-1404:~$ sudo apt-get changelog openssl | grep CVE-2014-0224
Helpful resource for Audacity.
    - debian/patches/CVE-2014-0224-regression2.patch: accept CCS after
# Different [http://manual.audacityteam.org/o/man/toolbars_overview.html Toolbars]
    - debian/patches/CVE-2014-0224.patch: set the CCS_OK flag when using
# [http://manual.audacityteam.org/o/man/tutorial_editing_an_existing_file.html Tutorial - Editing an Existing Audio File]
    - debian/patches/CVE-2014-0224-1.patch: only accept change cipher spec
    - debian/patches/CVE-2014-0224-2.patch: don't accept zero length master
    - debian/patches/CVE-2014-0224-3.patch: allow CCS after resumption in
    - CVE-2014-0224
</pre>
* [http://www.cyberciti.biz/faq/howto-openssl-security-update-cve20150291-cve20150204-cve20150290-cve20150207-cve20150286/ How To Patch and Protect OpenSSL Vulnerability # CVE-2015-0291 CVE-2015-0204 [19/March/2015]]


==== Let's Encrypt SSL ====
== Fade out at the end of an audio ==
[http://www.cyberciti.biz/faq/how-to-configure-nginx-with-free-lets-encrypt-ssl-certificate-on-debian-or-ubuntu-linux/ How to configure Nginx with free Let’s Encrypt SSL certificate on Debian or Ubuntu Linux]
# Select a region.
 
# Effect -> Fade out
=== Install webmin ===
* http://www.webmin.com/deb.html


= Wireshark =
* http://www.howtogeek.com/204458/why-you-shouldn%E2%80%99t-use-mac-address-filtering-on-your-wi-fi-router/
* http://www.howtogeek.com/191482/how-an-attacker-could-crack-your-wireless-network-security/
* http://www.howtogeek.com/104278/how-to-use-wireshark-to-capture-filter-and-inspect-packets/
<pre>
<pre>
apt-get install perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions python
sudo apt-get install wireshark
wget http://prdownloads.sourceforge.net/webadmin/webmin_1.600_all.deb
sudo chmod 4711 `which dumpcap`
dpkg --install webmin_1.600_all.deb
</pre>
</pre>
[[File:Webmin.png|100px]]
* [https://www.youtube.com/watch?v=8PuUnQCS7DQ Wireshark & Rtmpdump - Sniffing RTMP Streams - Ubuntu 10.10]


=== File does not exist: /var/www/favicon.ico from /var/log/apache2/error.log ===
= Track the Time a Command Takes =
The reason?  You have not created a favicon, also known as a website icon, for your website.  It’s the icon that displays in the address bar of your web browser when you connect to a website.  A web browser will request this icon file from every website.
[https://www.ostechnix.com/how-to-find-the-execution-time-of-a-command-or-process-in-linux/ How To Find The Execution Time Of A Command Or Process In Linux]


If you choose to create one. Use a program such as Gimp and create a 16×16 pixel image and save it as a .ico filetype.  Then upload that file to the DocumentRoot of your website.  You will need one for each VirtualHost.  If you don’t have Gimp, there are online resources  such as [http://www.favicon.cc/ favicon.cc] where you can create a .ico file and download it for your own use.
== time command ==
* [https://stackoverflow.com/a/556411 What do 'real', 'user' and 'sys' mean in the output of time(1)?]
* [https://www.howtoforge.com/linux-time-command/ Linux time Command Tutorial for Beginners (with Examples)]
{{Pre}}
time COMMAND
time (COMMAND1; COMMAND2)
time (COMMAND1 && COMMAND2)


As you know by now, not having a favicon.ico file, won’t stop web browsers from requesting it each time.  But you can tell Apache not to log the event as an error message.  You will still see the request in the access.log, but at least you will have a cleaner error.log file.
help time
 
</pre>
Add the following block of code to each VirtualHost, or at least the ones which don’t have a favicon file.


When I run a set of 7 jobs using parallel, time command gives an output
<pre>
<pre>
Redirect 404 /favicon.ico
real  15m53.788s # the wall clock time the command took from execution till termination
<Location /favicon.ico>
user  95m20.238s # the time taken by the user space
ErrorDocument 404 "No favicon"
sys  9m1.320s  # the time taken by kernel space
</Location>
</pre>
</pre>
Here we see the real time is about 16m and the user time is about 6-7 times the real time. Indicating the parallel executing works.


Don’t forget to restart apache after making the change. If you want make  a “global” change, which would apply to any and all VirtualHosts, you can create a file in Apache’s conf.d folder with a name such as nofavicon.conf and then add that block of code to the file.  That would disable favicon across the board and save you from having to edit each VirtualHost.
== /usr/bin/time command ==
'''[http://man7.org/linux/man-pages/man1/time.1.html /usr/bin/time]''' provides more information then ''time'' command.
{{Pre}}
man time
</pre>


Or, you create an empty file with the name “favicon.ico” in the directory root of Apache (for exemple /var/www/).
= Magazines =
* [http://www.linuxuser.co.uk/ Linux User & Developer]
* [http://www.linuxformat.com/ Linux Format]
* [http://www.linux-magazine.com/ Linux Magazine]
* [http://www.linuxjournal.com/ Linux Journal]


=== Show weather on the taskbar ===
= Latex =
http://www.noobslab.com/2012/10/important-thingstweaks-to-do-after.html


=== Screencaster/Record desktop ===
== Editors ==
* [https://itsfoss.com/Latex-editors-linux/ 10 Best LaTeX Editors For Linux].
* [http://www.xm1math.net/texmaker/ Texmaker]. R's installr package has a function to install Texmaker. Cross platforms.
* [https://www.tug.org/texworks/ TEXworks]. Cross platforms.
* [http://texstudio.sourceforge.net/ TexStudio]. See a dark theme [https://robjhyndman.com/hyndsight/dark-themes-for-writing/ example].


* RecordMyDesktop: http://www.youtube.com/watch?v=A0Tn3Z8OklQ. We need to run ffmpeg to convert video to flv (Quality seems to be reduced) OR we can use online service (http://video.online-convert.com/convert-to-mp4) to convert ogv file to mp4 file (Same quality as I can tell).
== Online editing ==
* https://wiki.ubuntu.com/ScreenCasts
* [https://latexbase.com/ Latex Base]. You can start to try it without registration. Free accounts cannot publish but still can download.
* [http://askubuntu.com/questions/107726/how-to-create-animated-gif-images-of-a-screencast Create animated Gif of a screencast] and the command line tool [https://github.com/jclem/gifify/ Gifify].
* [https://www.overleaf.com/ Overleaf]. Free account for 1GB space.
* [https://launchpad.net/kazam kazam]
* [https://www.sharelatex.com/ ShareLatex]


=== WebCam ===
== Missing cls ==
https://help.ubuntu.com/community/Webcam
* [http://packages.ubuntu.com/trusty/all/texlive-latex-extra/filelist texlive-latex-extra] packages and [http://packages.ubuntu.com/trusty/all/texlive-publishers/filelist texlive-publishers] packages.
* https://tex.stackexchange.com/questions/179214/elsarticle-cls-not-found-when-using-texmaker-but-texlive-latex-extra-is-install/179250
{{Pre}}
$ apt-cache search IEEEtran
texlive-publishers - TeX Live: Publisher styles, theses, etc.
</pre>
{{Pre}}
sudo apt-get install texlive-publishers
</pre>


Install '''cheese''' or '''guvcview'''. [https://thinkrpi.wordpress.com/2013/04/05/step-3-install-softwares-for-webcam-and-computer-vision/ An example of using computer vision] on Raspberry Pi.
== Missing sty ==
{{Pre}}
$ apt-cache search pseudocode
gpt - G-Portugol is a portuguese structured programming language
libgportugol-dev - Development files for the G-Portugol library
libgportugol0 - G-Portugol library
texlive-science - TeX Live: Natural and computer sciences
$ sudo apt-get install texlive-science
</pre>


=== Watch TV ===
= PDF =
[http://code.google.com/p/freetuxtv/wiki/HomePage?wl=en Freetuxtv]
See [[PDF|PDF]].


=== Running concrete5 On Nginx (LEMP) ===
= Flow chart =
http://www.howtoforge.com/running-concrete5-on-nginx-lemp-on-debian-squeeze-ubuntu-12.10
* LibreOffice Draw OR MS_PowerPoint (insert > shape). Check youtube.
* [https://www.yworks.com/products/yed yEd]
* [https://wiki.gnome.org/Apps/Dia/ Dia] & [https://en.wikipedia.org/wiki/Dia_%28software%29 wikipedia]
* (online) www.draw.io


=== Open mms stream in google chrom in linux ===
= Clock =
http://www.thermetics.net/2011/12/07/how-to-open-mms-links-from-chrome-under-ubuntu/
== xclock (analog) ==
{{Pre}}
oclock -geometry 500x500+100+0 &
</pre>


=== Download mms stream (suitable if mms is an extension; for example, studioclassroom) ===
== oclock (analog) ==
{{Pre}}
oclock -bg blue -geometry 500x500+100+0 -bd purple -transparent &
oclock -bg blue -geometry 500x500+100+0 -bd purple -jewel green &
</pre>
See [http://manpages.ubuntu.com/manpages/hardy/man1/oclock.1.html oclock], [http://manpages.ubuntu.com/manpages/hardy/man7/X.7.html X - a portable, network-transparent window system] which includes an example of specifying the ''geometry'' parameter.


* Use mimms (will NOT output to speaker at the same time; so is best in terms of performance)
== dclock (digital) ==
<pre>
Digital clock for the X Window System with flexible display.
sudo apt-get install mimms
* http://manpages.org/dclock
mimms -t 60 mms://example.com/video
* Note that we can send the command to the background using Ctrl +z and run '''bg'''. See [[#How_do_I_send_an_already-running_process_into_the_background|run a command from the terminal without blocking it?]]
<pre style="white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* IE 5.5+ */ " >
sudo apt-get install dclock
dclock -h
dclock -d
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139        # 'q' to quit
dclock -date "Today is %m/%d/%y" -led_off black -bg black -fg yellow -geometry 400x150+0+0 # width x hight + X + Y
</pre>
</pre>
where -t option specifies number of minutes. See http://linuxers.org/howto/how-download-mms-streaming-videos-ubuntu
In practice, I create a shell script file <bin/clock> with the following content. The first ampersand sign is to hide warnings messages and the 2nd ampersand sign is to put the process in the background.
The output will have the same extension as the input. But it is not always clear. For example
<pre style="white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* IE 5.5+ */ " >
<pre>
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139 &>/dev/null &
$ mimms -t 3 mms://bcr.media.hinet.net/RA000073                                                                                                   
mms://bcr.media.hinet.net/RA000073 => RA000073.wmv
1.48 MB / ∞ B (8.79 kB/s, ∞ s remaining)         
Download stopped after user-specified timeout.
</pre>
</pre>


== Lubuntu digital clock format ==
http://netgator.blogspot.com/2012/09/change-edit-panel-digital-clock-format.html. My format is
<pre>
%a, %x, %r
# Tue, 05/17/2016, 09:42:27 PM


* Use mplayer (will output to speaker at the same time, so suffer from performance, anyway do not get output)
%a %m-%d-%y, %I:%M %p
<pre>
# Mon 05-30-16, 08:31 AM
mplayer mms:/link/something.xxx -dumpstream -dumpfile file.xxx
</pre>
</pre>


mms:/link/something.xxx - link to the stream you wish to download
== xdaliclock (digital) ==
file.xxx - file to which you wish to download the stream, be careful to write the same extension xxx
https://www.mankier.com/1/xdaliclock
 
Wait for the file to download and that's it. See http://ubuntuhowtos.com/howtos/download_mms_stream


=== Keep a linux process running after log out ===
Scaling is not good. Colors is changing with time.
* http://linux.101hacks.com/unix/nohup-command/
{{Pre}}
* http://serverfault.com/questions/311593/keeping-a-linux-process-running-after-i-logout
xdaliclock -noseconds -cycle  # 'q' to quit
<pre>
# nohup command-with-options &
</pre>
</pre>


=== Open Firefox in cron job ===
== date command ==
The trick is to use '''export DISPLAY=:0'''
<pre>
<pre>
export DISPLAY=:0
sudo apt install toilet
firefox http://www.google.com &
sudo apt install figlet
</pre>
watch -n 60 "date +'%m/%d/%y  %H:%M:%S' | toilet"


=== Close firefox gracefully ===
ls /usr/share/figlet # list of fonts
Use '''wmctrl''' command.  
                    # looking for *.tlf
* http://www.linuxjournal.com/magazine/hack-and-automate-your-desktop-wmctrl
date +'%m/%d/%y%H:%M:%S' | toilet -f mono12
* http://tomas.styblo.name/wmctrl/
date +'%m/%d/%y%H:%M:%S' | toilet -f bigmono12  # good on 1024x600
<pre>
date +'%m/%d/%y%H:%M:%S' | toilet -f bigascii12
sudo apt-get install wmctrl
date +'%m/%d/%y%H:%M:%S' | toilet -f ascii12
wmctrl -c firefox
</pre>


=== Record audio out from command line ===
watch --color "date +'%m/%d/%y%H:%M:%S' | toilet -f bigmono12 -F metal"
http://www.pantz.org/software/alsa/recording_sound_from_your_web_browser_using_linux.html


Step 1: Install required programs
while true; do echo "$(date '+%H:%M:%S' | toilet -f bigmono12 -F border --metal)"; sleep 1; done
<pre>
sudo apt-get install gnome-media pavucontrol lame
</pre>
</pre>


Step 2: Create a script file <recordfm.sh>
= Reminder take a break, relieve eye strain =
<pre>
[https://github.com/hovancik/stretchly/ Stretchly]. It's open-source and cross-platform. Nodejs is required.
#!/bin/bash
# Get pulseaudio monitor sink monitor device then pipe it to
# sox to record wav, lame to encode to mp3, or flac to encode flac
FILENAME="$1"
STOPTIME="$2"
# Encoding options for lame and flac.
LAMEOPTIONS="--preset cbr 192 -s 44.1"


if [ -z "$FILENAME" ]; then
[http://www.workrave.org/ Workrave] is another choice. The source code is available too.
    echo -e "
    Usage: $0 /path/to/output.mp3
    Usage: $0 /path/to/output.mp3 stopinseconds" >&2
    exit 1
fi


# Get sink monitor:
[https://www.linuxuprising.com/2019/02/prevent-eye-strain-while-working-on.html?m=1 Prevent Eye Strain While Working On Your Linux Desktop With Safe Eyes], [https://slgobinath.github.io/SafeEyes/ Github] source code
MONITOR=$(pactl list | egrep -A2 '^(\*\*\* )?Source #' | \
    grep 'Name: .*\.monitor$' | awk '{print $NF}' | tail -n1)
echo "set-source-mute ${MONITOR} false" | pacmd >/dev/null


# Record it raw, and pipe to lame for an mp3
= wine =
echo "Recording to $FILENAME ..."
[[Wine|Wine]]


if [[ $FILENAME =~ .mp3$ ]]; then
= Running Linux in the AWS/Amazon Web Services =
  if [ -z $STOPTIME ]; then
* http://www.linuxuser.co.uk/tutorials/run-linux-in-the-aws-cloud
    parec -d $MONITOR | lame $LAMEOPTIONS -r - $FILENAME
  else
    echo -e "\nStopping in $STOPTIME seconds"
    parec -d $MONITOR | lame $LAMEOPTIONS -r - $FILENAME 2>&1 &
    SPID=$!
    sleep $STOPTIME
    kill -9 $SPID
  fi
fi
</pre>


Step 3: play the music or launch a browser with a desired url.
= Forum software =
* [http://www.simplemachines.org/ Simple Machines® Forum (SMF)]. For example http://pibot.org/forum/


Step 4: run the bash script
= RAID =
<pre>
* http://www.maximumpc.com/what-every-pc-builder-should-know-about-raid-levels/
chmod +x recordfm.sh
./recordfm.sh test.mp3 10
</pre>
where <test.mp3> is the output filename and 10 is recording length (seconds). It works.


Note the script teaches us how to find out the ID for a process we just launched (cleaner than using ps -ef | grep commands). The command is
= Timer =
<pre>
* http://zeegaree.com/. Require 3 libraries that we need to install them using apt-get install. See the [https://github.com/mivoligo/Zeegaree#zeegaree github] page.
SPID=$!
echo $SPID
</pre>


=== Use VLC to record internet radio (suitable if the stream is continuous) ===
= How to track you laptop using Prey =
<pre>
https://www.howtoforge.com/tutorial/how-to-track-your-linux-laptop/
sudo apt-get install vlc browser-plugin-vlc
</pre>


* http://ubuntuguide.org/wiki/Ubuntu:Precise#Restricted_Extras
= last command =
<pre>
[https://www.howtoforge.com/linux-last-command/ Linux last Command Tutorial for Beginners (8 Examples)]
sudo apt-get install ubuntu-restricted-extras
</pre>


* https://help.ubuntu.com/community/FFmpeg#Precise_Configurations
== Display a list of system shutdown/reboot date/time ==
[https://www.cyberciti.biz/tips/linux-last-reboot-time-and-date-find-out.html Linux Find Out Last System Reboot Time and Date Command]
<pre>
<pre>
sudo apt-get install lame  libmp3lame0
# Works on Linux and Mac
sudo apt-get install ffmpeg
last shutdown
sudo apt-get install libavcodec-extra-53 libavdevice-extra-53 libavfilter-extra-2 libavformat-extra-53 \
last reboot
                    libavutil-extra-51 libpostproc-extra-52 libswscale-extra-2
</pre>
</pre>


A successful run will have an output like
= Automatic reboot after power failure =
<pre>
It seems there is no reliable way to find out when the power failed.
VLC media player 2.0.3 Twoflower (revision 2.0.2-93-g77aa89e)
[0x2329ca8] dummy interface: using the dummy interface module...
[0x7fac2c007428] mux_dummy mux: Open
[0x7fac2c003598] access_mms access: selecting stream[0x1] audio (39 Kib/s)
[0x7fac2c003598] access_mms access: connection successful
[0x7fac2c003598] access_mms access error: failed to send command
[0x7fac2c005fe8] idummy demux: command `quit'
</pre>


=== Advanced audio control ===
The linux command 'last' can show some information about system reboot.
https://www.howtoforge.com/tutorial/advanced-audio-control-on-linux/


* Alsamixer
Another way is to modify the BIOS to select the option like 'Power off and Reboot'. This won't automatically boot your computer when it is shutdown normally.
* Pulse Audio Volume Control
* Pulse Audio Equalizer


=== Play audio using a command line mode ===
= How to restart/shutdown server safely =
See also my [[Beaglebone#Playing_music_using_command_line_tools|Beaglebone]] page for a comparison of different possibilities. For VLC, there are 3 [https://wiki.videolan.org/Console/ interface modes]. The following example is to run vlc in a text mode with the ncurses library.
[https://www.cyberciti.biz/faq/restart-centos-rhel-safely-and-gracefully/ How to restart CentOS or RHEL server safely]
<pre>
sudo apt-get install vlc-nox
vlc -I ncurses XXX.mp3
</pre>


=== Play youtube using VLC from a command line ===
= Wake up and Shut Down Linux Automatically =
See [http://raspberrypi.stackexchange.com/questions/1556/why-wont-flash-player-on-chromium-work this post]
* https://help.ubuntu.com/community/WakeOnLan
<pre>
* https://www.cyberciti.biz/faq/ubuntu-linux-wake-on-lan-client-command-installation-examples/
vlc -I http https://www.youtube.com/watch?v=UlW77conmAc
* [https://www.linux.com/learn/intro-to-linux/2017/11/wake-and-shut-down-linux-automatically Wake up and Shut Down Linux Automatically]
</pre>


=== SMPlayer ===
Two best options
* [http://www.ubuntugeek.com/install-smplayer-on-ubuntu-15-10.html Install SMPlayer on Ubuntu 15.10]
* Bios: BIOS may have an easy-to-use wakeup scheduler
* wakeonlan:
** Eanble it: Check if it is enabled by default. If not, we can 1) enable it through a command (ethtool -s eth0 wol g) or 2) using the Network Manager
** Send a wake up command: (from a second linux) '''/usr/bin/wakeonlan D0:50:99:82:E7:2B''' where D0:50:99:82:E7:2B is the IP on the machine you want to wake it up


=== CVS ===
= BIOS =
==== CVS server ====
== Find out BIOS version ==
<pre>
[https://www.cyberciti.biz/faq/check-bios-version-linux/ Linux Find Out BIOS Version Using a Command Line Option]
# Original data dir: /home/mli/Downloads/hmv_arc
# CVS dir on server (CVSROOT): /home/mli/cvsrep
# CVS dir on local:  /home/mli/Downloads/localcvs
# Project name: mycvs
# cvs user name: mli


sudo apt-get install cvs
== How to update Lenovo BIOS from Linux without using Windows ==
https://www.cyberciti.biz/faq/update-lenovo-bios-from-linux-usb-stick-pen/


mkdir ~/cvsrep
= Internet speed test =
export CVSROOT=/home/mli/cvsrep
== Web ==
cvs init
* https://fast.com/ (automatically run)
sudo groupadd mycvsgrp
* https://www.bing.com/search?q=internet+speed+test
sudo useradd -G mycvsgrp mli # Assume mli is a new user
* http://www.speedtest.net/
sudo usermod -a -G mycvsgrp mli  # assume mli is an existing user 
groups mli  # view groups a user is in use
sudo chown -R :mycvsgrp /home/mli/cvsrep # change the group ownership of cvsrep directory to mycvsgrp.
cd ~/Downloads/hmv_arc
cvs import -m "initial" mycvs mli START # import files to CVS repository
                                        # the new subfolder mycvs has owner mli.mli
</pre>
Note 1. It is OK to use the same CVSROOT for multiple modules/projects since each module/project will be saved under a separate subfolder.


Note 2. The cvs version that I have installed in my ubuntu server is 1.12.13.  
== Speedtest-cli ==
<pre>
See [[Raspberry#Track_Internet_Dropouts|Track_Internet_Dropouts]].
$ cvs -v


Concurrent Versions System (CVS) 1.12.13-MirDebian-6 (client/server)
{{Pre}}
</pre>
sudo apt-get intall python-pip
sudo pip install speedtest-cli
# A slightly modified code that will create a one-line space/semi-colon
# delimited result is
git clone https://github.com/HenrikBengtsson/speedtest-cli-extras.git


 
speedtest-cli-extras/bin/speedtest-csv
Quick test to checkout project to the same machine
<pre>
cd ~/Downloads
mkdir localcvs
cd localcvs
cvs checkout mycvs
</pre>
</pre>
This will create a new subfolder 'mycvs' under ~/Downloads/localcvs.
works. But if I want to put it in cron, cron will issue an error speedtest-cli cannot be found. So I need to modify line 52 of the code in <speedtest-cli-extras/bin/speedtest-csv> to explicitly specify the location of speedtest-cli.  
 
CVS repository on server has a structure
<pre>
<pre>
cvsrep/CVSROOT
    /usr/local/bin/speedtest-cli --share > $log
cvsrep/mycvs
</pre>
</pre>


CVS sandbox on local machine has a structure
NOTE: 1. the results differ from the network connection. For example, the speed is good when I test it on the machine directly connected to the router. 2. It is helpful to modify the last line of the bash script to output what I need. 3. The separator is ";" in the output.
<pre>
mycvs/CVS
mycvs/[files1]
mycvs/[files2]
</pre>


==== CVS client (ubuntu) ====
== curl and wget ==
'''Check out'''
[https://osxdaily.com/2013/07/31/speed-test-command-line/ How to Run Speed Test from the Command Line to Check Internet Connection Speed]
<syntaxhighlight lang='bash'>
cvs -d :ext:[email protected]:/home/mli/cvsrep checkout mycvs
# OR 2 steps
export CVSROOT=:ext:[email protected].net:/home/mli/cvsrep
cvs checkout mycvs
</syntaxhighlight>
 
'''Commit a new file'''
<syntaxhighlight lang='bash'>
cvs add mynewfile
cvs commit -m "my log message" mynewfile
</syntaxhighlight>


'''Update repository'''
= '''uname''' - Print system information =
<syntaxhighlight lang='bash'>
* https://www.lifewire.com/display-system-information-uname-command-3964321
cvs update -P -d
* [https://www.networkworld.com/article/3565432/how-to-decipher-linux-release-info.html How to decipher Linux release info]
# OR
cvs update filename
</syntaxhighlight>
where '''-P''' "prunes" directories that are empty, and '''-d''' tells cvs to include any new directories that aren't in your local workspace


'''Get a list of all tags and branches'''
'''uname -a''' will give you
<syntaxhighlight lang='bash'>
* OS (uname = uname -s if you are under a Linux environment)
# Lists all tags and braches for each and any file together with the revision it belongs to.
* '''OS (uname -s)''' eg Linux
cvs status -v
* node name (uname -n=hostname)
* '''kernel release (uname -r)''' eg 3.16.0-38-generic
* kernel version (uname -v)
* '''machine architecture (uname -m)''' eg x86_64
* processor (uname -p)
* hardware platform (uname -i)
* operating system (uname -o)


# http://stackoverflow.com/questions/566093/how-do-i-identify-what-branches-exist-in-cvs
[https://stackoverflow.com/questions/3466166/how-to-check-if-running-in-cygwin-mac-or-linux How to check if running in Cygwin, Mac or Linux?]
cvs log -h | awk -F"[.:]" '/^\t/&&$(NF-1)==0{print $1}' | sort -u
</syntaxhighlight>


'''Encoding of a file'''
= Hardware information =
<syntaxhighlight lang='bash'>
* [https://www.2daygeek.com/how-to-check-system-hardware-manufacturer-model-and-serial-number-in-linux/ How To Check System Hardware Manufacturer, Model And Serial Number In Linux]
$ cvs -d :ext:mli@taichi.selfip.net:/home/mli/cvsrep checkout mycvs
* [https://www.howtogeek.com/426199/how-to-list-your-computers-devices-from-the-linux-terminal/ How to List Your Computer's Devices From the Linux Terminal]: mount, lsblk, df, fdisk, /proc, lspci, lsusb, lsdev, lshw, lsscsi, dmidecode, hwinfo.
$ file -bi mycvs/src/hmvUnicode.rc
text/x-c; charset=utf-16le
</syntaxhighlight>


==== CVS client (windows) ====
== Command Line ==
I use WinCVS for a demonstration
* [https://opensource.com/article/19/9/linux-commands-hardware-information Linux commands to display your hardware information]
* Remote -> checkout module
* inxi: [https://opensource.com/article/22/9/linux-inxi-command 3 ways to use the Linux inxi command]
* Module name: mycvs
** '''inxi -b'''
* CVSROOT:
** '''inxi -W taipei,taiwan''' (check the weather)
**  protocol: ssh
* [https://ostechnix.com/how-to-find-your-system-details-using-inxi/ How To Find Linux System Details Using inxi]
**  repository path: /home/mli/cvsrep
** user name:
**  host name: taichi.selfip.net


If I use TortoiseCVS (1.12.5 from 1/24/2011), I need to choose ext as protocol instead ssh. Still the checked out file 'hmv_.rc' still contains unreadable Chinese characters. The cvsnt is the latest free version (2.5.05). If I want to use WinCVS + cvsnt from TortoiseCVS, the options in the CVSROOT dialog looks weird and cannot create a connection.
== hwinfo ==
https://www.2daygeek.com/python-hwinfo-check-display-system-hardware-configuration-information-linux/


For the unicode encoding. If I commit the file at first from ubuntu os, but check out in Windows. The checked out file has right encoding (using Notepad ++, or from VS2010). However, the file does not have right line ending and it shows Chineses character when I open it in either Notepad++ or VS2010.
On Ubuntu, use '''sudo apt install -y hwinfo''' to install hwinfo. [https://lindevs.com/install-hwinfo-on-ubuntu/ Install hwinfo on Ubuntu 20.04]
To see hidden characters in Linux, try either one of the following 2 methods:
* Open the file in EMACS and do a M-X hexl-mode
* geany editor.


The solution I have found to overcome accessing unicode (utf-16) file on Windows OS is using Cygwin.
== dmesg command ==
* Download setup.exe from http://cygwin.com/install.html
[https://www.howtogeek.com/449335/how-to-use-the-dmesg-command-on-linux/ How to Use the dmesg Command on Linux]
* Root directory = c:\cygwin
* Local package directory = C:\Users\brb\Downloads
* Direct connection
* Download site: ftp://cygwin.mirrors.pair.com (Some mirrors are not updated & contain old version of packages! For example, make sure the cvs version is 1.12.13.)
* Search: cvs. Click plus sign next to "Devel".  Click 'Skip' corresponding to cvs package.
* Search: ssh. Click plus sign next to "Net". Click 'skip' correspond to openssh package.
* Click 'Next' button.
* Click 'Finish' button.
* Now open 'Cygwin Terminal' icon on Windows Desktop.
<pre>
<pre>
export CVSROOT=:ext:[email protected]:/home/mli/cvsrep
sudo dmesg -L -T
cvs checkout mycvs
sudo dmesg -L -T --follow  # Watching Live Events
sudo dmesg -L -T | grep -i usb    # Search for a specific term
sudo dmesg | grep -E "memory|tty|dma"  # Search for multiple terms
</pre>
</pre>
The 'mycvs' directory should be under C:\cygwin\home\brb (a.k.a. /home/brb in cygwin) directory. We can open 'hmv_.rc' file in Notepad++ to double check if the file looks normal OR use md5sum to check.
where '''-L''' to is force color output and '''-T''' is to make timestamp human-readable.
 
==== Difference between CRLF (Windows), LF (Linux, Mac) and CR ====
This is a good summary I found: http://stackoverflow.com/questions/1552749/difference-between-cr-lf-lf-and-cr-line-break-types
 
* The Carriage Return (CR) character (0x0D, \r) moves the cursor to the beginning of the line without advancing to the next line. This character is used as a new line character in Commodore and Early Macintosh operating systems (OS-9 and earlier).
 
* The Line Feed (LF) character (0x0A, \n) moves the cursor down to the next line without returning to the beginning of the line. This character is used as a new line character in UNIX based systems (Linux, Mac OSX, etc)
 
* The End of Line (EOL) character (0x0D0A, \r\n) is actually two ASCII characters and is a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as a new line character in most other non-Unix operating systems including Microsoft Windows, Symbian OS and others.
 
==== Common CVS commands ====
* http://ximbiot.com/cvs/manual/
* http://mu2e.fnal.gov/public/hep/computing/cvsCheatSheet.shtml
* http://refcards.com/docs/forda/cvs/cvs-refcard-a4.pdf, http://www.bravegnu.org/cvscheat/cvscheat.pdf


= Linux Logo and the current system information =
* http://www.cyberciti.biz/hardware/howto-display-linux-logo-in-bash-terminal-using-screenfetch-linux_logo/
<pre>
<pre>
cvs checkout MODULE
odroid@odroid:~$ sudo apt-get install screenfetch
cvs checkout DIR
odroid@odroid:~$ screenfetch
cvs checkout DIR/SUBDIR
                          ./+o+-      odroid@odroid
cvs co DIR/SUBDIR/FILENAME
                  yyyyy- -yyyyyy+      OS: Ubuntu 15.10 wily
# check out a specific tag and put it in a specified directory.  
              ://+//////-yyyyyyo      Kernel: armv7l Linux 3.10.96-77
# the specified directory name will replace the module name in output.
          .++ .:/++++++/-.+sss/`      Uptime: 4d 23h 8m
mkdir localcvs
        .:++o:  /++++++++/:--:/-      Packages: 2000
cvs checkout -r v4_3 -d localcvs MODULE
        o:+o+:++.`..```.-/oo+++++/    Shell: 2263
 
      .:+o:+o/.          `+sssoo+/    Resolution: 1920x1080
cvs add myfile.c
  .++/+:+oo+o:`            /sssooo.  DE: MATE 1.10.2
cvs add -kb myfile.bin
/+++//+:`oo+o              /::--:.  WM: Metacity (Marco)
# If you accidentally add a file, simply skip the commit for that file.
\+/+o+++`o++o              ++////.  GTK Theme: 'Ambiant-MATE' [GTK2/3]
  .++.o+++oo+:`            /dddhhh.  Icon Theme: Ambiant-MATE
      .+.o+oo:.          `oddhhhh+    Font: Ubuntu 10
        \+.++o+o``-````.:ohdhhhhh+    CPU: ARMv7 rev 3 (v7l) @ 1.4GHz
        `:o+++ `ohhhhhhhhyo++os:      GPU: Gallium 0.4 on llvmpipe (LLVM 3.6, 128 bits)
          .o:`.syhhhhhhh/.oo++o`      RAM: 537MiB / 1990MiB
              /osyyyyyyo++ooo+++/   
                  ````` +oo+++o\:   
                          `oo++.    


cvs update –dA DIR/SUBDIR
odroid@odroid:~$ screenfetch -h
# -d: Create  any  directories  that  exist in the repository if they're missing from the working directory.
</pre>
# -A: Reset any sticky tags, dates, or -k options. Needed after you use "cvs update -D" or "cvs update -r".
* [https://github.com/dylanaraps/neofetch Neofetch], [[:File:NeofetchMac.png]], [[:File:Neofetchpopos.png]]
cvs update –A DIR/SUBDIR/FILENAME   


cvs commit
[[File:Neofetch.png|200px]]
cvs commit –m "add test suite" DIR/SUBDIR/FILENAME


mkdir ~/original
= Dictionary - [http://artha.sourceforge.net/wiki/index.php/Home Artha] =
touch ~/original/newfile
* [http://lifehacker.com/5916656/artha-is-a-feature-packed-offline-thesaurus-and-dictionary Lifehacker]. Once it is launched, it is sitting on the task bar. Press Ctrl+Alt+W after selecting a word to look it up in Artha (a balloon tip will pop up on the screen top-right). It also supports using regular expressions to search words.
cvs import ~/original VENDORTAG RELEASETAG
{{Pre}}
 
sudo apt-get install artha
mkdir ~/localcvs
</pre>
cd ~/localcvs
cvs checkout common/too


cvs diff -r1.23 -r1.24 SUBDIR/FILENAME    # Difference between specified versions 1.23 & 1.24.
== Translation ==
cvs diff -D "1 hour ago" MODULE
* [https://www.soimort.org/translate-shell/ Translate Shell]. No installation is needed. It is just a bash script (4990 lines) so it works on ODroid SOC. See also [https://www.2daygeek.com/translate-shell-a-tool-to-use-google-translate-from-command-line-in-linux/ A Tool To Use Google Translate From Command Line In Linux]
cd LOCALCVS; cvs diff
{{Pre}}
cvs checkout -D "1 hour ago" MODULE
odroid@odroid:~/binary$ ./trans :zh-TW word
cvs checkout -D "2013-02-27 01:30" MODULE
word
/wərd/


rm file(s); cvs remove file(s); cvs commit -m "Comment text" file(s)
# You must rm the file before issuing the cvs remove command. The remove is not final until the commit has been issued.
()


# cvs does not let you remove directories. However it does let you ignore any directories that are empty.
Definitions of word
cvs co -P Offline
[ English -> 正體中文 ]
cvs update -PdA
# P: Prune empty directories. d: create new directories. A: Reset sticky tags


cvs history -c -a -D "1 day ago"  -z "-0500"
noun
# find all changes submitted to the repository by anyone in the past day.
    字
# -z is used to adjust the time zone.
        word, character, letter, calligraphy, symbol, style of writing
    詞
        word, term, speech, statement
    單詞
        word, individual word
    話
        words, word, dialect, saying, talk, speech
    言
        word, speech, character
    言辭
        words, word, what one says
    筆墨
        pen and ink, words, word, writings
    約言
        pledge, promise, word


cvs history -c -a -D "1 day ago" -f Mu2eG4/src
verb
# find all changes submitted to Mu2eG4/src (or any other subdirectory) by anyone in the past day
    為 ... 措辭
        word
odroid@odroid:~/binary$ time ./trans -brief :zh-TW word


cvs history -c -u USER "1 day ago" -f Mu2eG4/src
real 0m4.249s
# find all changes submitted by USER to Mu2eG4/src in the past day
user 0m2.670s
 
sys 0m1.330s
cvs log FILENAME
</pre>
</pre>


=== Bypass SSH password login (convenient for CVS, git etc) ===
= ASCII art/ word art =
http://www.howtogeek.com/tips/bypass-ssh-logins-by-adding-your-key-to-a-remote-server-in-a-single-command/
* figlet. [https://www.tecmint.com/create-ascii-text-banners-in-linux-terminal/ How to Create ASCII Text Banners in Terminal], [https://www.tecmint.com/lolcat-command-to-output-rainbow-of-colors-in-linux-terminal/ lolcat]
 
* toilet command. '''date | toilet''' . [https://www.linuxbots.com/print-awesome-ascii-text-in-linux-terminal/#Changing_the_color_of_Output Color output]. '''man toilet'''. TOIlet  prints  text using large characters made of smaller characters. It is similar in many ways to FIGlet with additional features  such  as Unicode handling, colour fonts, filters and various export formats.
# ssh-keygen -t rsa
* http://patorjk.com/software/taag/#p=display&f=Ivrit&t=BRR-SeqTools
# (make sure the remote server has .ssh directory)
<pre>
# cat ~/.ssh/id_rsa.pub | ssh user@hostname 'cat >> .ssh/authorized_keys'
  ____  ____  ____      ____            _____          _   
# ssh user@hostname
| __ )|  _ \| __ )    / ___|  ___  __ |_  _|__  ___ | |___
 
|  _ \| |_) | _ \ ____\___ \ / _ \/ _` || |/ _ \ / _ \| / __|
It helps with CVS log in too when the CVS works by using ssh protocol. Note that step 3 allows to run a shell command at a remote machine.
| |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
 
|____/|_| \_\____/     |____/ \___|\__, ||_|\___/ \___/|_|___/
See https://help.github.com/articles/generating-ssh-keys also for similar instruction when work on github.
                                      |_|                   
 
The ssh key can be copied to another a machine (pay attention to mode). Or let the new machine to create its own key pair and use '''ssh-copy-id''' to append the identity file to remote  machine's ~/.ssh/authorized_keys file. See http://superuser.com/questions/332510/how-to-transfer-my-linux-ssh-keys-to-another-machine.
 
We can even have multiple ssh key on local machine by using. ssh/config file. See
http://www.karan.org/blog/index.php/2009/08/25/multiple-ssh-private-keys.
 
=== Install Ubuntu to a USB flash drive ===
The following approach assumes the boot loader will not be put on internal hard disk if you are careful enough. See also http://fernhilllinuxproject.com/guidesandhowtos/installubuntutousbdrive.html
 
# Boot from live CD in ubuntu.
# Insert the USB flash drive in USB Port.
# On desktop double click on icon 'install ubuntu 12.04'
# Click on continue and it will ask if you want to unmount the flash drive click on yes
# Choose some thing else when ask to where to install ubuntu.
# Next you will see your hard disk partitions and flash drive. Click on flash drive partition and then click on change. Change the partition type to ext4 and mount as to '/'. Click on ok to close the dialogue box.
# In last you will see a drop down menu on where to install the the boot loader. Initially it will be showing sdc,sdd but on drop down you must select sdc1 or sdd1. Failing this step you may render your computer unbootable.
# Then click on install and linux will be installed on your USB Flash drive.
 
=== Install a new hard drive ===
https://help.ubuntu.com/community/InstallingANewHardDrive
# Use sudo fdisk command to create partition table. Then 'n', 'p', '1', 'w' and several returns.
# Use sudo mkfs -t ext4 /dev/sdb1 to create a new partition
# Use sudo mkdir /mnt/ssd to create a new mount point
# Use sudo nano -Bw /etc/fstab to do auto mount on boot
# sudo chown -R USERNAME:USERNAME /mnt/ssd to give the ownership to the USERNAME.
 
=== Building a simple Beowulf Like Cluster with Ubuntu ===
See also the [[Raspberry#Clustering|Raspberry Pi]] page where a simple cluster was built.
 
==== MPICH2 ====
Resource:
# http://byobu.info/article/Building_a_simple_Beowulf_cluster_with_Ubuntu/
# https://help.ubuntu.com/community/MpichCluster
# https://help.ubuntu.com/community/SettingUpNFSHowTo (NFS configure)
 
Here is my record for creating a cluster environment based on ubuntu 13.04. The master node is running on ubuntu 13.04 desktop with virtualBox 4.2. The virtualBox has added a host-only adapter (vboxnet0) with ip 192.168.56.1. This adapter will be added to the master node so I can use this ip to identify the master node in the host-only network. Creating cluster using VirtualBox is just for the education purpose, not for real practice.
 
* (virtualBox) Create two virtual machines running on ubuntu 13.04 server. The ssh server was checked during installation. The host name for each of them is ubuntuNode1 and ubuntuNode2 respectively. The network adapter is left by default (NAT) during installation. But after the installation is done, I shutdown the system and add a host-only adapter (vboxnet0) to each of them. Then after the system is up again, I change the IP so it is static. Do '''sudo nano /etc/network/interfaces''' and append the following before running '''sudo /etc/init.d/networking restart''' to take the change in effect.
<pre>
auto eth1
iface eth1 inet static
address 192.168.56.101 # use 192.168.56.102 for ubuntuNode2
netmask 255.255.255.0
network 192.168.56.0
broadcast 192.168.56.255
</pre>
</pre>
Note that it is better not to add host-only network before installation, or during installation it will ask what is the primary network (confusing). So at the end each new nodes should have both '''eth0''' and '''eth1''' adapters and they should not reside in same subset. '''ifconfig''' may not show all adapters so we should use '''ifconfig -a''' instead. Although host-only network is used for communication between guest and guest OR guest and host, since each guest node has NAT adapter by default so the guest machine can still access the internet.
* http://patorjk.com/software/taag/#p=display&f=Big&t=BRB-SeqTools
* (master node) Edit /etc/hosts so it like like
<pre>
<pre>
127.0.0.1 localhost
  ____  _____  ____        _____        _______          _   
192.168.56.1 ubuntu1304
|  _ \|  __ \|  _ \      / ____|      |__  __|        | |   
192.168.56.101 ubuntuNode1
| |_) | |__) | |_) |____| (___  ___  __ _| | ___  ___ | |___
192.168.56.102 ubuntuNode2
|  _ <|  _  /|  _ <______\___ \ / _ \/ _` | |/ _ \ / _ \| / __|
| |_) | | \ \| |_) |    ____) |  __/ (_| | | (_) | (_) | \__ \
|____/|_|  \_\____/    |_____/ \___|\__, |_|\___/ \___/|_|___/
                                        | |                   
                                        |_|                   
</pre>
</pre>
Note that the master node will be used to start jobs on the cluster although it is OK to let the master node as one of nodes to execute the jobs.
* http://patorjk.com/software/taag/#p=display&f=Small&t=BRB-SeqTools
* (all nodes) Run
<pre>
<pre>
sudo adduser mpiuser --uid 999
  ___ ___ ___    ___          _____        _   
| _ ) _ \ _ )___/ __| ___ __ |_  _|__  ___| |___
| _ \  / _ \___\__ \/ -_) _` || |/ _ \/ _ \ (_-<
|___/_|_\___/  |___/\___\__, ||_|\___/\___/_/__/
                            |_|                 
</pre>
</pre>
It is recommeneded to use the same password for the user. This will create a new directory ''/home/mpiuser''. This is the home directory for user ''mpiuser'' and we will use it to execute jobs on the cluster.
* (master node) Run
<pre>
sudo apt-get install nfs-kernel-server
</pre>
* (other nodes) Run
<pre>
sudo apt-get install nfs-client
</pre>
* (master node) Add the following to the file '''/etc/exports'''
<pre>
/home/mpiuser *(rw,sync,no_subtree_check)
</pre>
or something like
<pre>
/home/mpiuser 192.168.56.0/24(rw,sync,no_subtree_check)
</pre>
Some people create a shared folder under /srv directory.


Now run
= Install And Manage Software From Source =
<pre>
[https://ostechnix.com/install-and-manage-software-from-source-using-gnu-stow/ How To Install And Manage Software From Source Using GNU Stow In Linux]
sudo service nfs-kernel-server restart
 
</pre>
= Software that scan Malware and rootkits =
* (master node)
* https://www.howtoforge.com/tutorial/how-to-scan-linux-for-malware-and-rootkits/
<pre>
sudo ufw allow from 192.168.56.0/24
</pre>
* (other nodes)
<pre>
sudo mount ubuntu1304:/home/mpiuser /home/mpiuser
</pre>
And if we want to mount the NFS shared directory when the compute nodes are booted, edit '''/etc/fstab''' by adding
<pre>
ubuntu1304:/home/mpiuser /home/mpiuser nfs
</pre>
* (master node)
<pre>
sudo apt-get install ssh
su mpiuser
ssh-keygen
ssh-copy-id localhost
</pre>
We can test if the ssh works without passwords
<pre>
ssh ubuntuNode1
echo $HOSTNAME
</pre>
* (all nodes)
<pre>
sudo apt-get install mpich2
which mpirun
which mpiexec
</pre>
* (master node, mpiuser)
Go to the home directory of mpiuser and create a new file '''hosts'''. Include host names for computing nodes (it is OK to include master node, ubuntu1304, as one of computing nodes)
<pre>
ubuntuNode1
ubuntuNode2
</pre>
* (all nodes)
<pre>
sudo apt-get install build-essential
</pre>
* (master node, mpiuser). Creating a test file <mpi_hello.c>
<pre>
#include <stdio.h>
#include <mpi.h>


int main(int argc, char** argv) {
= Text to speech =
    int myrank, nprocs;
* http://www.eguidedog.net/ekho.php. Compilation/build works on x86 Ubuntu 14 and Odroid Ubuntu 15.10. On Odroid I have to follow their instruction to use 'make CXXFLAGS=-DNO_SSE' instead of 'make'. However, sound feels shaky on Odroid xu4.  
 
* http://audiobookmaker.com/
    MPI_Init(&argc, &argv);
* http://project-modelino.com/online-resources-category.php?site_language=english&learn_language=chinese&category=tts
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
 
    printf("Hello from processor %d of %d\n", myrank, nprocs);
 
    MPI_Finalize();
    return 0;
}
</pre>
And compile and run it by
<pre>
mpicc mpi_hello.c -o mpi_hello
mpiexec -n 3 -f hosts ./mpi_hello
</pre>
We should see something like
<pre>
Hello from processor 0 of 2
Hello from processor 1 of 2
</pre>
Successful! That's it.
 
==== OpenMPI ====
* http://auriza.site40.net/notes/mpi/openmpi-on-ubuntu-904/
* http://particlephysicsandcode.wordpress.com/2012/11/04/installing-open-mpi-1-6-3-ubuntu-12-04-fedora/
* http://randomusefulnotes.blogspot.com/2010/12/setting-up-mpi-cluster-on-ubuntu.html
 
With R
* http://www.open-mpi.org/papers/tr-uni-muenchen-8991/parallelR_techRep.pdf
* http://www.cybaea.net/Blogs/R-tips-Installing-Rmpi-on-Fedora-Linux.html (Fedora)
* http://kiradi.blogspot.com/2011/10/high-performance-computing-with-openmpi.html (Ubuntu)
* http://cran.r-project.org/web/packages/doMPI/vignettes/doMPI.pdf
* http://biowulf.nih.gov/user_guide.html#parallel
 
=== File sharing in a local network - woof ===
* https://www.howtoforge.com/tutorial/linux-how-to-share-files-on-a-local-network/
 
=== Sharing internet ===
==== Sharing internet via wifi: ap-hotspot ====
I cannot make it to work to share the internet via wifi on my Xubuntu 13.04. However the solution in http://askubuntu.com/questions/287251/creating-an-infrastructure-hotspot-using-ubuntu-12-10 works for me.
<syntaxhighlight lang='bash'>
$ # Under rare situation, we need to run the following line to get 'add-apt-repository'
$ sudo apt-get install apt-get install software-properties-common
$ sudo su -
# add-apt-repository ppa:nilarimogard/webupd8
# aptitude update
# aptitude install ap-hotspot
# ap-hotspot configure
# ap-hotspot start
</syntaxhighlight>
In the step of 'ap-hotspot configure' it will ask for Access Point name and WPA passphrase.
 
When I run the final line 'ap-hotspot start', it will ask me to disconnect my current wifi first.
 
At the end, I found my original configuration in ubuntu does not work even its setting is there. '''apt-hotspot''' create an infrastracture AP instead of adhoc.
 
==== Sharing internet via wifi: iptables ====
1. Assume the primary wired network connection, eth0 is connected to Internet.
 
2. Using your distro's network managment tool, create a new ad hoc wireless connection with the following settings:
<pre>
IP address: 10.99.66.55
Subnet mask: 255.255.0.0 (16)
</pre>
 
3. Use the following shell script to share the internet connection
<syntaxhighlight lang='bash'>
#!/bin/bash
#filename: netsharing.sh
#Replace 10.99.0.0/16 by your network/netmask
#Usage: ./netsharing.sh input_interface output_interface
#Example: ./netsharing.sh eth0 wlan0
 
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -A FORWARD -i $1 -o $2 -s 10.99.0.0/16 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A POSTROUTING -t nat -j MASQUERADE
</syntaxhighlight>
 
4. Run the script as follows:
<syntaxhighlight lang='bash'>
./netsharing.sh eth0 wlan0
</syntaxhighlight>
 
5. Connect your devices to the wireless network you just created with the following settings:
<pre>
IP address: 10.99.66.56 (and so on)
Subnet mask: 255.255.0.0
</pre>
 
To make this more convenient, you might want to install a DHCP and DNS server on your machine, so it's not necessary to configure IPs on devices manually. A handy tool for this is '''dnsmasq''' which you can use for performing both DHCP and DNS operations.
 
Credit: Linux Shell Scripting Cookbook.
 
==== iptables ====
* [[Beaglebone#Internet_over_USB|Beaglebone]]
 
=== ~/.xsession-errors file is filling the hard disk ===
It is related to vino-server. See
* http://askubuntu.com/questions/130768/my-home-partition-slowly-fills-up-until-the-system-is-unable-to-complete-even-si
* http://filthypants.blogspot.com/2013/02/xsession-errors-log-filling-hard-drive.html
 
Short solution is to use "kill -9 xxx" to kill the process and rm to remove ~/.xsession-errors file. The long time solution is to uninstall vino.
 
=== JRE and JDK ===
Install openjdk or Sun jdk. See http://www.maketecheasier.com/install-java-runtime-in-ubuntu/ (Ubuntu 12.04)
 
If we have multiple versions of JRE/JDK, we can use the [https://www.digitalocean.com/community/tutorials/how-to-install-java-on-ubuntu-with-apt-get following command] to set the default version
<pre>
sudo update-alternatives --config java
</pre>
This approach seems to be working in the case JAVA_HOME cannot be honored.
 
==== OpenJDK ====
On my Ubuntu 12.04, I have two versions.
<syntaxhighlight lang='bash'>
$ whereis java
java: /usr/bin/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz
$ java -version
java version "1.6.0_38"
 
$ sudo apt-get -y install openjdk-7-jdk
$ ls -l /usr/lib/jvm
total 12
lrwxrwxrwx 1 root root  20 Nov 16  2013 java-1.6.0-openjdk-amd64 -> java-6-openjdk-amd64
lrwxrwxrwx 1 root root  20 Mar 24 06:20 java-1.7.0-openjdk-amd64 -> java-7-openjdk-amd64
drwxr-xr-x 7 root root 4096 Feb 20 08:43 java-6-openjdk-amd64
drwxr-xr-x 3 root root 4096 Jan 31  2014 java-6-openjdk-common
drwxr-xr-x 7 root root 4096 Mar 30 18:16 java-7-openjdk-amd64
 
$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 Jan 31  2014 /usr/bin/java -> /etc/alternatives/java
</syntaxhighlight>
 
Question: [http://askubuntu.com/questions/64329/how-to-replace-openjdk-6-with-openjdk-7 how to switch to 1.6 or 1.7 version of java?] (For example, snpEff requires java 1.7)
<syntaxhighlight lang='bash'>
$ update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1051 /usr/lib/jvm/java-1.7.0-openjdk-amd64
$ sudo apt-get install icedtea-7-plugin
$ sudo update-java-alternatives -s java-1.7.0-openjdk-amd64
update-java-alternatives: plugin alternative does not exist: /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/IcedTeaPlugin.so
$ update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1051 /usr/lib/jvm/java-1.7.0-openjdk-amd64
$ java -version
java version "1.7.0_95"
</syntaxhighlight>
 
==== Oracle JAVA ====
http://askubuntu.com/questions/521145/how-to-install-oracle-java-on-ubuntu-14-04
<pre>
sudo apt-add-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
 
java -version
</pre>
 
=== CPU/system load ===
* CPU-G: See [http://blog.hostonnet.com/how-to-view-cpu-info-in-ubuntu-cpu-z-alternative-for-linux this instruction] to install CPU-G program for viewing hardware information (process, mb, graphic, memory, system).
 
* [http://www.howtogeek.com/118908/10-awesome-indicator-applets-for-ubuntus-unity-desktop/ System Load Indicator]: it is used to view system information (cpu, memory, network) in real-time.
<pre>
sudo apt-get install indicator-multiload
</pre>
 
=== Hard drive specification ===
http://www.cyberciti.biz/faq/find-hard-disk-hardware-specs-on-linux/
 
<syntaxhighlight lang='bash'>
# hdparm command
sudo hdparm -I /dev/sda
 
# OR using lshw command
sudo apt-get install lshw
lshw -class disk -class storage
 
# Find Out Disks Name Only
lshw -short -C disk
</syntaxhighlight>
 
=== Hard disk speed (3.0 or 6.0 Gb/s) ===
http://www.cyberciti.biz/faq/freebsd-command-to-find-sata-link-speed/
<syntaxhighlight lang='bash'>
$ dmesg | grep -i SATA
[    0.311173] pci 0000:00:11.0: set SATA to AHCI mode
[    1.510881] ahci 0000:00:11.0: AHCI 0001.0200 32 slots 4 ports 6 Gbps 0xf impl SATA mode
[    1.512669] ata1: SATA max UDMA/133 abar m1024@0xfe02f000 port 0xfe02f100 irq 19
[    1.512672] ata2: SATA max UDMA/133 abar m1024@0xfe02f000 port 0xfe02f180 irq 19
[    1.512675] ata3: SATA max UDMA/133 abar m1024@0xfe02f000 port 0xfe02f200 irq 19
[    1.512677] ata4: SATA max UDMA/133 abar m1024@0xfe02f000 port 0xfe02f280 irq 19
[    1.832349] ata4: SATA link down (SStatus 0 SControl 300)
[    1.832418] ata2: SATA link down (SStatus 0 SControl 300)
[    2.004290] ata3: SATA link up 6.0 Gbps (SStatus 133 SControl 300)
[    2.004313] ata1: SATA link up 3.0 Gbps (SStatus 123 SControl 300)
</syntaxhighlight>
 
To test the disk performance, follow [http://www.cyberciti.biz/faq/howto-linux-unix-test-disk-performance-with-dd-command/ cyberciti.biz]. Note that the parameter '''oflag=dsync''' makes a difference.
 
Here I have a 7200rpm Seagate (ST2000DM001-1CH164) and a 5400rpm WD-blue (WD30EZRZ-00WN9B0)
<syntaxhighlight lang='bash'>
# Hard disk info https://en.wikipedia.org/wiki/Hdparm
sudo hdparm -I /dev/sda
sudo hdparm -I /dev/sdb
 
# Writing speed, where /tmp is a directory from the disk
dd if=/dev/zero of=/tmp/test1.img bs=2G count=1; rm /tmp/test1.img
# 1.4 GB/s from either 5400 or 7200 rpm
 
dd if=/dev/zero of=/tmp/test1.img bs=2G count=1 oflag=dsync; rm /tmp/test1.img
# 115 MB/s from 5400 rpm
# 166 MB/s from 7200 rpm
 
# Latency
dd if=/dev/zero of=/tmp/test2.img bs=512 count=1000 oflag=dsync; rm /tmp/test2.img
# 27.7 kB/s from 5400 rpm  <==== This is interesting
# 12.5 kB/s from 7200 rpm
 
# Read speed
dd if=/dev/zero of=/tmp/test3.img bs=1G count=1 oflag=direct; rm /tmp/test3.img
# 122 MB/s from 5400 rpm
# 180 MB/s from 7200 rpm
</syntaxhighlight>
 
=== Hard disk directory size ===
See [[Linux#Display_directory_size_with_sorting_and_human_readable|Display directory size with sorting and human readable]] by using the '''ncdu''' utility.
 
=== Monitor harddisk health by command line ===
Using [https://www.howtoforge.com/tutorial/monitor-harddisk-with-smartmon-on-ubuntu/ smartctl].
 
=== Hard disk temperature ===
http://www.cyberciti.biz/tips/howto-monitor-hard-drive-temperature.html
 
It seems the hddtemp command does not work on SSDs.
<pre>
sudo apt-get install hddtemp
sudo hddtemp /dev/sdb
 
/dev/sdb: ST2000DM001-9YN164: 40°C
</pre>
 
For SSD,
<pre>
sudo apt-get install smartmontools
sudo smartctl -a /dev/sda
</pre>
 
=== Hard disk power on time/hours ===
<syntaxhighlight lang='bash'>
sudo smartctl --all /dev/sda | grep Power_On_Hours
</syntaxhighlight>
Sample output:
<pre>
$ sudo smartctl -A /dev/sda | grep -i power
  9 Power_On_Hours          0x0032  034  034  000    Old_age  Always      -      58541
12 Power_Cycle_Count      0x0032  100  100  020    Old_age  Always      -      164
$ sudo smartctl -A /dev/sdb | grep -i power
  9 Power_On_Hours          0x0032  100  100  000    Old_age  Always      -      585
12 Power_Cycle_Count      0x0032  100  100  000    Old_age  Always      -      43
192 Power-Off_Retract_Count 0x0032  200  200  000    Old_age  Always      -      32
</pre>
 
=== system's hardware temperatures and voltages ===
https://www.howtoforge.com/tutorial/ubuntu-performance-monitoring/
<pre>
sudo apt-get install lm-sensors
sensors
 
brb@brb-P45T-A:~$ sensors
acpitz-virtual-0
Adapter: Virtual device
temp1:        +30.0°C  (crit = +110.0°C)
 
coretemp-isa-0000
Adapter: ISA adapter
Core 0:      +41.0°C  (high = +78.0°C, crit = +100.0°C)
Core 1:      +36.0°C  (high = +78.0°C, crit = +100.0°C)
 
nouveau-pci-0100
Adapter: PCI adapter
temp1:        +68.0°C  (high = +95.0°C, hyst =  +3.0°C)
                      (crit = +125.0°C, hyst =  +3.0°C)
                      (emerg = +135.0°C, hyst = +10.0°C)
</pre>
And on a Dell T3600 machine (running the samtools mpileup & bcftools programs),
<pre>
brb@T3600 ~ $ sensors
nouveau-pci-0300
Adapter: PCI adapter
fan1:        3510 RPM
temp1:        +52.0°C  (high = +95.0°C, hyst =  +3.0°C)
                      (crit = +105.0°C, hyst =  +5.0°C)
                      (emerg = +135.0°C, hyst =  +5.0°C)
 
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0:  +70.0°C  (high = +81.0°C, crit = +91.0°C)
Core 0:        +60.0°C  (high = +81.0°C, crit = +91.0°C)
Core 1:        +60.0°C  (high = +81.0°C, crit = +91.0°C)
Core 2:        +56.0°C  (high = +81.0°C, crit = +91.0°C)
Core 3:        +60.0°C  (high = +81.0°C, crit = +91.0°C)
Core 4:        +70.0°C  (high = +81.0°C, crit = +91.0°C)
Core 5:        +60.0°C  (high = +81.0°C, crit = +91.0°C)
</pre>
 
=== Unlock keyring ===
I got the prompt of unlocking keyring every time I open google chrome browser.
 
* http://askubuntu.com/questions/867/how-can-i-stop-being-prompted-to-unlock-the-default-keyring-on-boot (this works)
* http://askubuntu.com/questions/184266/what-is-unlock-keyring-and-how-do-i-get-rid-of-it (this does not help)
* http://superuser.com/questions/311216/why-does-chrome-ask-for-my-gnome-keyring-seahorse-password (works. I create a shortcut to launch chrome)
<pre>
google-chrome --password-store=basic
</pre>
It is also helpful to remove ubuntu one from Ubuntu 12.04. See http://hex.ro/wp/blog/removing-ubuntuone-from-ubuntu-12-04/
 
=== netcat (nc) - arbitrary TCP and UDP connections and listens ===
Netcat or nc is a networking utility for debugging and investigating the network.
 
The nc (or netcat) utility is used for just about anything under the sun involving TCP, UDP, or UNIX-domain sockets.  It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.
 
* http://www.thegeekstuff.com/2012/04/nc-command-examples/
* https://www.digitalocean.com/community/tutorials/how-to-use-netcat-to-establish-and-test-tcp-and-udp-connections-on-a-vps
* https://learn.adafruit.com/raspipe-a-raspberry-pi-pipeline-viewer-part-2?view=all
 
For example, we can create simple network sockets and use them for text communication. We need two sockets: one listens for connections and the other connects to this one.
<syntaxhighlight lang='bash'>
# create a listening socket on the local machine
nc -l 1234
 
# connect to the socket from a 2nd computer
nc IP_LocalMachine 1234
 
# send messages.
# Type something and press Enter on the terminal from the 2nd computer.
# The message will appear on the terminal of the local machine.
</syntaxhighlight>
 
To transfer files over the network ('''no any password is needed!!''')
<syntaxhighlight lang='bash'>
# receiver machine
nc -l 1234 > destination_file
 
# sender machine
nc IP_Receiver 1234 < source_filename
</syntaxhighlight>
 
=== List of all services/daemons ===
Run service '''--status-all''' to get a list off all the Upstart services and their status. See
* man service
* man initctl
<pre>
service --status-all  # output format is clean
 
sudo initctl list      # show the process number too
</pre>
where in the output "+" means started, "-" stopped, and "?" unknown.
 
=== Google Drive ===
<pre>
sudo add-apt-repository ppa:thefanclub/grive-tools
sudo apt-get update
sudo apt-get install grive-tools
</pre>
On Dash, type grive. It will ask you to enter a sequence of characters. After that, a new folder 'Google Drive' will be created and files will be downloaded.
 
* http://www.thefanclub.co.za/how-to/ubuntu-google-drive-client-grive-and-grive-tools
* http://www.thefanclub.co.za/node/151
 
=== Video rip/convert/transcoder ===
* [https://handbrake.fr/ Handbrake]
<pre>
sudo add-apt-repository ppa:stebbins/handbrake-releases
sudo apt-get update
sudo apt-get install handbrake-gtk
 
sudo apt-get install handbrake-cli
</pre>
 
* libav-tools
To convert youtube flv file to mp4.
<pre>
sudo apt-get install libav-tools
avconv -i INPUT.flv -codec copy OUTPUT.mp4
</pre>
 
To extract audio only:
<pre>
avconv -i INPUT.flv -codec copy -vn OUTPUT.mp4
</pre>
 
* ffmpeg [https://www.virag.si/2012/01/web-video-encoding-tutorial-with-ffmpeg-0-9/ method]
 
=== Video editing in Linux ===
* https://wiki.ubuntu.com/ScreenCasts/VideoEditing
* http://opensource.com/life/15/1/current-state-linux-video-editing
* http://www.makeuseof.com/tag/top-6-free-video-editors-mac-os/
 
==== [http://www.pitivi.org/ Pitivi] ====
 
==== [http://www.blender.org/ Blender] ====
 
==== [https://kdenlive.org/ Kdenlive] ====
 
==== [http://www.openshot.org/ OpenShot] ====
An article from [http://www.pcworld.com/article/230531/free_openshot_video_editor_is_tremendous.html PC World].
<syntaxhighlight lang='bash'>
sudo apt-get install openshot
</syntaxhighlight>
When I needed to export the video (choose 'youtube' profile, 'youtube-HD' target, 'HD 270, 29 .97 bps', and 'high' quality), I found I need to install [https://answers.launchpad.net/openshot/+faq/1040 libx264 code]. On Ubuntu, I open software center and seach 'libavformat'. I choose 'libavformat-extra-53'.
 
[https://www.howtoforge.com/tutorial/an-introduction-to-video-editing-in-openshot-2-0/ An introduction to video editing in Openshot 2.0] from howtoforge.
 
==== [https://trac.videolan.org/vlmc/ VideoLAN Movie Creator] ====
 
==== [http://ffdiaporama.tuxfamily.org/ ffdiaporama] ====
Create videos from images, movie clips and music.
 
=== Youtube command line tools ===
* Download youtube video
<syntaxhighlight lang='bash'>
sudo apt-get install youtube-dl
</syntaxhighlight>
* Fix the error 'WARNING: Your copy of avconv is outdated and unable to properly mux separate video and audio files, youtube-dl will download single file media. Update avconv to version 10-0 or newer to fix this.':
(works) http://askubuntu.com/questions/563245/avconv-warning-while-downloading-youtube-video
<syntaxhighlight lang='bash'>
$ sudo add-apt-repository ppa:heyarje/libav-11 && sudo apt-get update
$ sudo apt-get install libav-tools
</syntaxhighlight>
(not tested) [https://forums.linuxmint.com/viewtopic.php?t=197316 Compile your own]. The source code is available at https://libav.org/.
* For videos with 1080p resolution, youtube-dl will download 720p by default. To download 1080p, see [http://askubuntu.com/questions/486297/how-to-select-video-quality-from-youtube-dl this post]
<syntaxhighlight lang='bash'>
youtube-dl -f 137+141 XXXX
</syntaxhighlight>
* To convert the video to mp3 format, use soundconverter
<syntaxhighlight lang='bash'>
sudo apt-get install soundconverter
</syntaxhighlight>
* [http://www.webupd8.org/2014/11/youtube-command-line-player-and.html Play/Download youtube video] using [https://github.com/np1/mps-youtube mps-youtube]
<syntaxhighlight lang='bash'>
mps-youtube
</syntaxhighlight>
* 4k videos [http://www.imaging-resource.com/news/2014/11/19/samsung-nx1-4k-video-samples-and-new-full-res-frame-grabs-available-for-do samples] (vlc v2.1.4 cannot play)
 
=== Unity LauncherSwitcher ===
[http://www.ubuntugeek.com/unity-launcherswitcher-allow-users-to-set-up-different-workspaces-for-different-task-categories.html Ubuntugeek.com]
 
=== Create Unity Launcher ===
Take RStudio for example,
 
* [http://askubuntu.com/questions/127290/setting-program-logo-in-unity-launcher-missing-icons-folder Desktop icons] are saved under '''/usr/share/icons/hicolor/16x16/apps/'''rstudio.png, where other than 16x16 there are also icons from 24x24, 32x32, 48x48 sizes (directories). Another place is '''~/.local/share/icons/hicolor/16x16/''' .
* [https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles Unity launcher] is created at '''/usr/share/applications/'''rstudio.desktop or '''~/.local/share/applications/'''XXXX.desktop.
* Desktop shortcut can be created by copy XXXX.desktop to ~/Desktop directory.
 
The icon size in the launcher can be adjusted by opening System Settings -> Apperance -> Launcher Icon Size (at the bottom).
 
[http://www.willus.com/k2pdfopt/help/ubuntu.shtml k2pdfopt] has an example how to do it for creating a desktop shortcut and be in the right click menu.
 
=== Remove floppy icon from Launcher ===
http://askubuntu.com/questions/457970/how-to-completely-disable-floppy-in-ubuntu-14-04
 
<syntaxhighlight lang='bash'>
echo "blacklist floppy" | sudo tee /etc/modprobe.d/blacklist-floppy.conf
sudo rmmod floppy
sudo update-initramfs -u
</syntaxhighlight>
 
=== How to Convert the Unity Launcher into a Dock-Style Launcher ===
See an article from [http://www.howtogeek.com/202708/how-to-convert-the-unity-launcher-into-a-dock-style-launcher/ Howtogeek.com].
 
=== What date was the system installed ===
<pre>
ls -l /var/log/installer
</pre>
 
=== What is the last log in time for users ===
<pre>
lastlog  # all users
last    # current user
</pre>
 
=== What is the reboot time ===
<pre>
last reboot
</pre>
 
=== Crop an image ===
<pre>
sudo apt-get install gthumb
</pre>
Open an image. Click color palette icon on top-right corner (or use keyboard shortcut 'e'). Click 'crop'. There will be a rectangle on image where you can resize the rectangle.
 
=== Mind-mapping ===
* [http://www.xmind.net/ xmind]
* [http://freemind.sourceforge.net/wiki/index.php/Main_Page FreeMind]
 
=== KeePass ===
Search Ubuntu Software Center to install [http://www.keepassx.org KeePassX] (more reviews) or [http://keepass.info KeePass2]. There is no need to use ppa.launchpad.net to install from. Note that the kdbx file used in KeePass2 cannot be opened in KeePassX. To use the command line to install KeePass2,
<pre>
sudo apt-get install keepass2
</pre>
 
Note:
* Android: KeePassDroid
* Chrome: [https://chrome.google.com/webstore/detail/chromeipass/ompiailgknfdndiefoaoiligalphfdae?hl=en ChromeIPass] with KeePassHttp. See the [https://github.com/pfn/passifox/ source code].
 
=== Update Firefox ===
See https://help.ubuntu.com/community/FirefoxNewVersion. The following instruction is used to get security-testing packages.
<pre>
sudo add-apt-repository ppa:ubuntu-mozilla-security/ppa
sudo apt-get update
sudo apt-get install firefox
</pre>
 
=== Bluetooth ===
* https://wiki.debian.org/BluetoothUser
* https://help.ubuntu.com/community/BluetoothSetup
* [http://askubuntu.com/questions/474839/bluetooth-is-disable-on-ubuntu-14-04 To turn Bluetooth ON when your systeem starts up]
* [http://raspberrypi.stackexchange.com/questions/934/how-do-i-install-bluetooth-for-my-mouse-and-keyboard How to install bluetooth for my mouse and keyboard] for my Raspberry Pi.
<syntaxhighlight lang='bash'>
sudo apt-get install bluetooth
sudo apt-get install bluetooth bluez-utils blueman
</syntaxhighlight>
Then run '''lsusb | grep Bluetooth''' command which will shows the name of your bluetooth device.
 
* https://wiki.archlinux.org/index.php/Bluetooth
<syntaxhighlight lang='bash'>
sudo apt-get install bluez
</syntaxhighlight>
 
On my bluetooth adapter, the '''lsusb''' shows,
<syntaxhighlight lang='bash'>
$ lsusb
Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
...
$ sudo hcitool dev
Devices:
hci0 00:1A:7D:DA:71:09
</syntaxhighlight>
 
I can use Ubuntu's bluetooth setting dialog to connect my bluetooth keyboard without any problem (It will ask me to enter some code on pairing).
 
Note that the MAC address of my bluetooth keyboard shown above is the from the controller/adapter. It is NOT the same as my bluetooth keyboard one (90:7F:61:8F:D0:38) as shown from the bluetooth setting (GUI) dialog.
 
=== Change default audio player ===
Right-click an MP3 file, and from the menu select “Properties”. In the window that appears, go to the “Open With” tab and select VLC or whatever. Click the “Set As Default” button to set VLC as the default player.
 
You might also want to set the default player in the sound menu.
 
=== Unity display timeout ===
Go to [http://www.techotopia.com/index.php/Image:Ubuntu_11_unity_battery_power_management_settings.jpg Dash -> power setting -> Brightness Settings]
 
=== Screensaver showing current time ===
==== xscreensaver + gltext ====
http://askubuntu.com/questions/64086/how-can-i-change-or-install-screensavers
 
<pre>
sudo apt-get install xscreensaver
# sudo apt-get remove gnome-screensaver
</pre>
Click Dash > xscreensaver or run the command line '''xscreensaver-demo'''. Mode = Only One Screen Saver & pick GLText. Click Setting & choose 'Display date and time' ,'Don't rotate'.
 
==== gluqlo ====
[Note that gluqlo uses too much cpu]
I like [https://github.com/alexanderk23/gluqlo gluqlo (flip clock) screensaver]. However, it is not easy to make it to replace the gnome-screensaver.
<pre>
sudo apt-add-repository ppa:alexanderk23/ppa
sudo apt-get update
sudo apt-get install gluqlo
</pre>
* Follow the instruction to install it on Ubuntu machine.
* Follow the instruction there to remove gnome-screensaver and install xscreensaver.
* Configure xscreensaver to use only 1 screensaver. Edit ~/.xscreensaver file and add a line like
<pre>
gluqlo -root                                \n\
</pre>
* Still follow the instruction to allow xscreensaver to start when the machine starts up. Don't try to edit ~/.xinitrc file as other sites suggested; start Dash and type 'startup' and follow the screen dialog to add xscreensaver -nosplash.
* Still follow the instruction to add lock screen keyboard shortcut.
 
Note that the above steps work for Ubuntu 12.04 & 13.10 but not 14.04 (Ubuntu 14.04 changed to use LockScreen instead LightDM program to lock the screen). A solution on Ubuntu 14.04 is to [http://askubuntu.com/questions/465194/how-to-disable-screen-lock-in-ubuntu-14-04-unity disable screen lock].
 
# Still follow the above instruction to remove gnome-screensaver and install xscreensaver. Set gluqlo as the only one screensaver.
# Go to Brightness & Lock panel from the Unity Launcher. And set Turn screen off when inactive: to ''Never''.
# Install "Unity Tweak Tool" with sudo apt-get install unity-tweak-tool. Run it from the Launcher and select System > Security > Enhance system security by disabling Desktop lock.
# To enable locking desktop (required a password to unlock the desktop), check 'Lock Screen After' option. I pick 1 minute.
 
For some reason, gluqlo suddenly uses all my cpu (6 cores) resource (Ubuntu 14.04). The computer thus makes some noise. I have to use 'kill' command to kill them.
 
=== Flash for browser ===
* https://help.ubuntu.com/community/RestrictedFormats/Flash
* http://www.howtogeek.com/193876/using-firefox-on-linux-your-flash-player-is-old-and-outdated/
 
On Ubuntu 12.04, there is no way to directly install the pepperflashplugin-nonfree plugin. So we have to use ppa from other people. See [http://linuxg.net/how-to-install-chromium-and-enable-pepper-flash-plugin-on-all-the-supported-ubuntu-systems-and-their-derivatives/ this post]
<pre>
sudo apt-get update
sudo apt-get install chromium-browser
sudo add-apt-repository ppa:skunk/pepper-flash
sudo apt-get update
sudo apt-get install pepflashplugin-installer
sudo update-pepperflashplugin-nonfree --install
</pre>
The last step gives me an error: sudo: update-pepperflashplugin-nonfree: command not found
 
=== Gedit ===
* To split a screen, Do "Documents -> New Tab Group. No extra plugin is needed to download. I am using version 3.10.4 from Ubuntu 14.04.
* [https://github.com/Quixotix/gedit-restore-tabs Restore tabs] plugin. It works on my gedit 3.4 (ubuntu 12.04). Follow the instruction there exactly.
* [https://github.com/Quixotix/gedit-source-code-browser Source code browser] plugin. This makes gedit a good IDE for developing C++/Java code since the left panel can show symbols. Click F9 to show the side panel.
* [https://raw.githubusercontent.com/mig/gedit-themes/master/darkmate.xml Darkmate theme].
<pre>
cd /usr/share/gtksourceview-3.0/styles
sudo gedit darkermate.xml
</pre>
gedit > Edit > preferences > font and colors > color scheme.
* Gedit has no built-in options to show special characters except through [https://wiki.gnome.org/GeditPlugins gedit-plugins] (sudo apt-get install gedit-plugins). See [http://stackoverflow.com/questions/17162851/option-to-display-control-characters-in-gedit Draw Spaces].
 
=== [http://www.geany.org/ Geany] ===
Geany has a way to show special characters (Tabs/LF/CR). Edit > Preferences > Display > Tick, Show whitespace (tabs) & Show Line endings(CR/LF).
 
For DOS text file, the line ending is CR+LF.
 
For Unix text file, the line ending is LF.
 
[https://en.wikipedia.org/wiki/Newline A DOS/Windows text file can be converted to Unix format by simply removing all ASCII CR characters with]
<pre>
$ tr -d '\r' < inputfile > outputfile  # inputfile and outputfile cannot be the same
</pre>
or, if the text has only CR newlines, by converting all CR newlines to LF with
<pre>
$ tr '\r' '\n' < inputfile > outputfile
</pre>
 
'''Geany''' can be used to run a bash script file line by line. See [[Linux_Programming#Debugging_Scripts|Debugging_Scripts]].
 
==== Remove vertical line ====
Edit -> Preferences -> Editor -> Display -> Uncheck Long line marker.
 
=== HTML editor ===
* [http://kompozer.net/ Kompozer] and the installation instruction for [https://help.ubuntu.com/community/InstallKompozer Ubuntu].
* [http://bluegriffon.org/ BlueGriffon]: a new WYSIWYG content editor. The interesting thing is the software [http://www.bluegriffon-epubedition.com/BGEE.html BlueGriffon EPUB Edition]: a cross-platform Wysiwyg editor able to natively create and edit EPUB2 and EPUB3 ebooks!
 
=== chm reader ===
<pre>
sudo apt-get install xchm
</pre>
 
=== SCR3310 smart card ===
* https://help.ubuntu.com/community/CommonAccessCard
<syntaxhighlight lang='bash'>
sudo apt-get install libpcsclite1 pcscd pcsc-tools
lsusb
# Bus 006 Device 002: ID 04e6:5116 SCM Microsystems, Inc. SCR331-LC1 / SCR3310 SmartCard Reader
dmesg | grep SCR3310
# [ 2005.300052] usb 6-1: Product: SCR3310 v2.0 USB SC Reader
</syntaxhighlight>
* Search "SCR3310 driver linux" on google.com.
<pre style="white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;">
# Download pcsc-lite-1.8.13.tar.bz2 from
# https://alioth.debian.org/frs/?group_id=30105
sudo apt-get install libudev-dev
cd pcsc-lite-1.8.13
./configure
make
sudo make install
 
# Download libusb
http://libusb.info/
cd libusb-1.0.19
./configure
make
sudo make install
 
# Download scmccid_5.0.27_linux
# http://www.identive-infrastructure.com/index.php/products-solutions/smart-card-readers-a-terminals/smart-card-readers/scr3310
 
cd scmccid_5.0.27_l32r
sudo ./install.sh
</pre>
 
* Search "activcard driver linux" on google.com.
** https://militarycac.com/linux.htm
 
=== Chroot ===
* https://help.ubuntu.com/community/BasicChroot
* https://help.ubuntu.com/community/DebootstrapChroot
* http://www.thegeekstuff.com/2010/01/debootstrap-minimal-debian-ubuntu-installation/
* http://www.binarytides.com/setup-chroot-ubuntu-debootstrap/ (Works after a little change)
 
Note that we have to change the conf file a little bit. The 'location' word needs to be changed to 'directory'. Also at the last step when we are ready to test a 32-bit GUI app, we need to issue DISPLAY in a separate line; such as
<pre>
export DISPLAY=:0.0
su brb # brb is my root user in the host system that can invoke the schroot program
      # firefox does not allow to use root to start it
firefox
</pre>
For a recap:
<pre>
1. Install the packages
sudo apt-get install debootstrap schroot -y
2. Create a schroot configuration file
sudo nano /etc/schroot/chroot.d/precise_i386.conf
3. Install 32-bit ubuntu with debootstrap
sudo mkdir -p /srv/chroot/precise_i386
sudo debootstrap --variant=buildd --arch=i386 precise /srv/chroot/precise_i386 http://archive.ubuntu.com/ubuntu/
4. Test the chroot environment
schroot -l
schroot -c precise_i386 -u root
uname -a
cat /etc/issue
5. Additional configuration
apt-get install ubuntu-minimal
# That's all.
</pre>
 
The article also mentioned the home directories (Documents, Downloads, ...) of the users within the chroot are shared with the host. How to access them from the host?
 
* [https://blog.night-shade.org.uk/2013/12/building-a-pure-debian-armhf-rootfs/ Building a pure Debian armhf rootfs]
* [https://www.stgraber.org/2012/02/03/ever-wanted-an-armel-or-armhf-container-on-an-x86-machine-its-now-possible-with-lxc-in-ubuntu-precise/ Create an armhf container on your x86 machine?]
 
=== Check/Diagnostic SD card ===
http://askubuntu.com/questions/69932/is-there-an-sd-card-diagnostic-utility
 
Look for Disk Utility on you dash (Alt+F2 and type 'disk')
 
=== [https://developer.ubuntu.com/en/snappy/ Ubuntu Snappy Core] ===
==== How Snappy packages are different from Deb ====
An article from [http://www.pcworld.com/article/2942267/why-ubuntu-plans-to-replace-traditional-linux-packages-with-something-better.html PCWorld]
 
* Applications are no longer installed system-wide. The base Ubuntu operating system is kept securely isolated from applications you install later. Both the base system and Snappy packages are kept as read-only images.
* Snappy packages can include all the libraries and files they need, so they don’t depend on other packages.
* An update can never fail, as a package installation could potentially fail and become incomplete with typical Linux packages.
* Snappy also supports “delta” updates, which means only the changed bits of the package need to be downloaded and installed.
* Snappy-based Ubuntu systems might be standard.
 
==== Docker ====
I haven't found any tutorial yet!
 
==== Ova image ====
Sorry, I don't get the command line back. Booting stuck in the middle.
 
==== Beaglebone ====
http://beagleboard.org/snappy or http://www.ubuntu.com/things#try-beaglebone
 
==== Raspberry Pi 2 ====
https://darrenjw2.wordpress.com/2015/02/07/getting-started-with-snappy-ubuntu-core-on-the-raspberry-pi-2/
 
=== unable to open mtp device ubuntu 14.04 ===
[http://askubuntu.com/questions/463015/ubuntu-14-04-and-android-cant-see-phone-on-my-computer Use this tip].
<pre>
sudo apt-get install mtpfs
</pre>
 
=== Install/upgrade google chrome browser ===
<pre>
wget -N https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
</pre>
Note that '-N' option.
 
(Mar 7, 2016). We may experience an error "Failed to fetch http://dl.google.com/linux/chrome/deb/dists/stable/Release" when we run sudo apt-get update. It is because the 32-bit chrome has been discontinued. The solution is to modify the file </etc/apt/sources.list.d/google-chrome.list>. See [https://www.reddit.com/r/chrome/comments/48oje6/linux_how_to_fix_failed_to_fetch/ reddit].
 
=== Message of the day /etc/motd ===
https://wiki.debian.org/motd
 
=== .Trash-1000 folder ===
See [http://superuser.com/questions/169980/what-is-trash-and-trash-1000 this post]. Ubuntu will create such folders when a file is deleted from a USB drive. Presumably this would allow a file to be restored if you accidentally deleted it.
 
Try to empty the paperbin or delete the folder with the terminal-command as root: sudo rm -rf /path/to/folder/.Trash-1000
 
=== Xbox wireless Gamepad ===
https://www.howtoforge.com/tutorial/how-to-configure-your-gamepad-on-ubuntu/
 
=== [https://github.com/baedert/corebird Corebird] - a twitter client ===
* https://gist.github.com/arraytools/4d1af59a7ebd58ab3941 (tested on Ubuntu 14.04)
 
== RHEL/CentOS ==
 
=== Change hostname ===
* Change the ^HOSTNAME line in /etc/sysconfig/network
* Change the hostname in /etc/hosts
* Run /bin/hostname new_hostname for the hostname change to take effect immediately.
* Run /sbin/service syslog restart for syslog to log using the new hostname.
 
Note that using the command line 'hostname' to change the machine's hostname works only for the current session.
 
=== Check CentOS version ===
<syntaxhighlight lang='bash'>
$ cat /etc/redhat-release
CentOS Linux release 7.2.1511 (Core)
</syntaxhighlight>
 
=== switch to root ===
<pre>
su  # Press 'Enter'. It will ask for root's password.
</pre>
 
=== sudoer ===
Some distributions do not come with sudo command.
 
As root type:
 
visudo
 
and add a line
<pre>
MyUserName ALL = ALL
</pre>
 
=== Add an existing user to have sudo privilege ===
<pre>
sudo adduser USERNAME sudo
</pre>
See [https://help.ubuntu.com/community/RootSudo help.ubuntu.com].
 
=== What is my IP address ===
<pre>
ifconfig eth0
</pre>
 
=== What is my DNS server ===
<pre>
/etc/resolv.conf
</pre>
 
=== What services get started at boot time ===
<pre>
chkconfig --list
</pre>
 
=== Is xxx service running ===
<pre>
xxx status
</pre>
 
=== What services are currently running ===
<pre>
ps -e
</pre>
and
<pre>
lsof -i
</pre> will show you services that are listening to TCP or UDP endpoints.


=== Open ports in a firewall ===
= VPN =
* http://ask.xmodulo.com/open-port-firewall-centos-rhel.html
[[Ubuntu#VPN|Ubuntu -> VPN]]


On CentOS/RHEL 7.
= [http://www.mono-project.com/ Mono Project] =
<syntaxhighlight lang='bash'>
'''Mono''' is a software platform designed to allow developers to easily create cross platform applications part of the .NET Foundation
# Open port 80
sudo firewall-cmd --zone=public --add-port=80/tcp --permanent
sudo firewall-cmd --reload
# Check the updated rules with:
firewall-cmd --list-all
</syntaxhighlight>


On CentOS/RHEL 6
Mono is required for [https://www.repetier.com/download-now/ Repetier-Host] software for 3D printing.
<syntaxhighlight lang='bash'>
# Open port 80
sudo iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT
sudo service iptables save
</syntaxhighlight>


To check
= NAS server =
<syntaxhighlight lang='bash'>
== OpenMediaVault ==
$ netstat -tulpn | grep 8787
[[NAS#OpenMediaVault|OpenMediaVault]]
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:8787            0.0.0.0:*              LISTEN      -                 
$ netstat -tulpn | grep 80
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp6      0      0 :::80                  :::*                    LISTEN      - 
</syntaxhighlight>


=== Routing table ===
== [http://www.freenas.org/ FreeNAS] ==
How to read the routing table?
ZFS system (FreeBSD-based).
* http://www.cyberciti.biz/faq/what-is-a-routing-table/
* http://www.cyberciti.biz/faq/linux-unix-osx-bsd-windows-0-0-0-0-network-address/


Ubuntu wireless adapter:
[http://www.makeuseof.com/tag/reasons-storing-data-freenas/ 10 Reasons Why You Should Store Your Data on a FreeNAS Box]. Note With the current version of FreeNAS (FreeNAS 11) comes a '''hypervisor'''. See
<syntaxhighlight lang='bash'>
* https://doc.freenas.org/11/vms.html
brb@brb-P45T-A:~$ netstat -rn
* https://forums.freenas.org/index.php?threads/freenas-11-0-released.55327/
Kernel IP routing table
* [http://www.freenas.org/blog/yes-you-can-virtualize-freenas/ Virtualize FreeNAS]
Destination    Gateway        Genmask        Flags  MSS Window  irtt Iface
* [https://wiki.freebsd.org/bhyve bhyve, the BSD Hypervisor]
0.0.0.0        192.168.1.1    0.0.0.0        UG        0 0          0 wlan0
* [https://forums.servethehome.com/index.php?threads/freenas-as-hypervisor-host.4888/ FreeNAS as hypervisor host]
192.168.1.0    0.0.0.0        255.255.255.0  U        0 0          0 wlan0
</syntaxhighlight>


Ubuntu virtual machine:
= Change detection =
<syntaxhighlight lang='bash'>
http://bhfsteve.blogspot.com/2013/03/monitoring-web-page-for-changes-using.html
brb@vm-1404:~$ netstat -rn
Kernel IP routing table
Destination    Gateway        Genmask        Flags  MSS Window  irtt Iface
0.0.0.0        10.0.2.2        0.0.0.0        UG        0 0          0 eth0
10.0.2.0        0.0.0.0        255.255.255.0  U        0 0          0 eth0
192.168.1.0    0.0.0.0        255.255.255.0  U        0 0          0 eth1
brb@vm-1404:~$ ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 08:00:27:ee:7d:45 
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:feee:7d45/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:831 errors:0 dropped:0 overruns:0 frame:0
          TX packets:558 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:578902 (578.9 KB)  TX bytes:55508 (55.5 KB)


brb@vm-1404:~$ ifconfig eth1
= 3 command-line tools for feigning productivity =
eth1      Link encap:Ethernet  HWaddr 08:00:27:cb:96:6c 
https://opensource.com/article/18/2/command-line-tools-productivity: [https://github.com/yaronn/blessed-contrib Blessed-contrib] (javascript), Genact, Hollywood.
          inet addr:192.168.1.244  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fecb:966c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:84 errors:0 dropped:0 overruns:0 frame:0
          TX packets:54 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:8287 (8.2 KB) TX bytes:8966 (8.9 KB)
</syntaxhighlight>


A default gateway is set as follows:
= Mind mapping =
<syntaxhighlight lang='bash'>
* [https://www.freeplane.org/wiki/index.php/Home Freeplane]
route add default gw IP_ADDRESS INTERFACE_NAME


route add default gw 192.168.0.1 wlan0
= Diagram =
</syntaxhighlight>
* [https://www.calligra.org/flow/ Calligra Flow]. Microsoft Visio alternative.


=== What network ports are open ===
= Open source surveillance =
<pre>
[https://www.zoneminder.com/downloads/ ZoneMinder]
lsof -i
</pre>
or
<pre>
netstat -aut
</pre>


=== What firewall rules do I in place ===
= Systemctl, systemd =
<pre>
* Linux 系统开机启动项清理 [https://linux.cn/article-8835-1.html 中文] & [https://www.linux.com/learn/cleaning-your-linux-startup-process English]
iptables -L
* [https://www.tecmint.com/chkservice-manage-systemd-units-in-terminal/ Chkservice – An Easy Way to Manage Systemd Units in Terminal]
</pre>
* [[Raspberry#Use_a_systemd_unit.2Fservice_file_to_control_an_application_to_start_when_Raspberry_pi_boots_up|Control an application to run when Raspberry pi boots up]]
See [http://www.cyberciti.biz/tips/linux-iptables-examples.html this article]: 20 Iptables Examples For New SysAdmins from cyberciti.biz.
* [https://www.howtogeek.com/675569/why-linuxs-systemd-is-still-divisive-after-all-these-years/ Why Linux’s systemd Is Still Divisive After All These Years]
 
* [https://www.howtoforge.com/how-to-manage-systemd-services-with-systemctl/ How to Manage Systemd Services with Systemctl on Linux]
=== What packages do I have installed ===
** Manage Services with Systemd
<pre>
** Manage Systemd Unit Files
rpm -qa | less
** Manage Sockets with Systemctl
</pre>
** Systemctl Additional Commands
or
<pre>
rpm -qa | grep xxx
</pre>
 
=== What version of package xxx do I have installed ===
<pre>
rpm -qi xxx
</pre>
 
=== List of available (uninstalled) packages ===
<pre>
yum list available
</pre>
 
=== List All Configured Repositories ===
<pre>
yum -v repolist
yum -v repolist | less
yum repolist
</pre>


To list only enabled repositores
== Systemd vs SysVinit ==
<pre>
* https://kernelmastery.com/systemd-vs-sysvinit/
yum repolist enabled
* https://linoxide.com/linux-command/systemd-vs-sysvinit-cheatsheet/
</pre>
* https://www.2daygeek.com/sysvinit-vs-systemd-cheatsheet-systemctl-command-usage/


To list only disabled repositories
== Systemctl vs service commands ==
<pre>
[https://serverfault.com/a/867334 What is the difference between service and systemctl?] '''service''' is an "high-level" command used for starting and stopping services in different unixes and linuxes. Depending on the "lower-level" service manager, service redirects on different binaries. For example, on CentOS 7 it redirects to '''systemctl'''.
yum repolist disabled
</pre>


To list available packages under a repo called ksplice-uptrack, enter:
<pre>
<pre>
yum --disablerepo="*" --enablerepo="ksplice-uptrack" list available
$ service nginx start
</pre>
# VS
$ systemctl start nginx


=== yum equivalent of apt-get update ===
$ systemctl  # list all services
<pre>
$ cat /lib/systemd/system/rsyslog.service
yum check-update
$ systemctl status rsyslog
$ cat /lib/systemd/system/ufw.service
</pre>
</pre>


=== Open a port ===
== How to Run a Linux Program at Startup with systemd ==
 
<ul>
Edit the file '''/etc/sysconfig/optables'''. Create a new rule by following the examples of other rules in the file.
<li>[https://www.howtogeek.com/687970/how-to-run-a-linux-program-at-startup-with-systemd/ How to Run a Linux Program at Startup with systemd]
 
* Creating the Service Program for systemd to Start '''sudo nano /usr/local/bin/htg.sh''',  '''sudo chmod +x /usr/local/bin/htg.sh'''
=== sendmail ===
* Creating the Service Unit File '''sudo nano /etc/systemd/system/htg.service''', '''sudo chmod 640 /etc/systemd/system/htg.service'''
* [https://sachinsharm.wordpress.com/2013/08/19/setting-up-sendmail-on-centosrhel-6-3/ Install sendmail on centos]
* Starting the Service Automatically with the systemd Command '''sudo systemctl daemon-reload''', '''sudo systemctl enable htg''', '''sudo systemctl start htg'''
* [http://ithelpblog.com/itapplications/howto-fix-postfixsmtp-network-is-unreachable-error/ Ipv4]
* Verifying the Service '''sudo systemctl status htg.service'''
* Stopping and Disabling the Service - '''sudo systemctl stop htg.service'''
<li>[https://www.makeuseof.com/create-systemd-service-on-linux/ How to Create a New systemd Service on Linux]
<li>[https://dmpop.xyz/article.php?id=2024-10-29_systemd-mount-dev Automatically mount a storage device with a systemd service]
</ul>


== How Long Does it Take To Boot Your Linux System ==
[https://itsfoss.com/check-boot-time-linux/ Find Out How Long Does it Take To Boot Your Linux System]
<pre>
<pre>
su                            # type your root password to switch the account
$ systemd-analyze      # total boot time along with the time taken by
yum install m4 telnet mailx
                        # firmware, boot loader, kernel and the userspace
yum install sendmail sendmail-cf
$ systemd-analyze blame # breakdown the boot time into each unit
nano /etc/mail/sendmail.mc
m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
service sendmail restart
netstat -an | grep :25 | grep tcp
ps -ef | grep -v grep | grep -i sendmail
nano /etc/mail/local-host-names
service sendmail restart
chkconfig sendmail on
useradd testuser1
useradd testuser2 
passwd testuser2
mail -s "Test mail from testuser1" testuser2
tail /var/log/maillog
su testuser2 # run 'mail' command to see if the mail has been received.
 
nano /etc/mail/local-host-names # create a line, says, xyz.com
nano /etc/mail/sendmail.cf      # After the line of "Smart" relay host (may be null), edit as the following
                                # DSmailfwd.nih.gov
nano /etc/postfix/main.cf #  change inet_protocols from all to ipv4.
nano /etc/sysconfig/sendmail    # make sure DAEMON=yes
nano /etc/mail/relay-domains    # this is a new file with 1 line 128.231.90.107
service sendmail restart
mail -s "Test mail from testuser1" [email protected]
tail /var/log/maillog          # Should not see any ERR.
netstat -nutlap | grep 25
</pre>
</pre>


=== Power Manager for GNOME ===
== Check if Your Linux System Uses systemd ==
 
[https://itsfoss.com/check-if-systemd/ How to Check if Your Linux System Uses systemd]
'''The configuration defaults for GNOME power manager have not installed correctly. Cannot login'''
 
This error will results in a log-in problem except root account. The symptom is 50GB in root (/) is used up.
 
The problem was caused by a bug in yum where '''/var/cache/yum/x86_64/6Workstation''' takes about 42GB space. The 'yum' does not remove old generated .sqlite files.
 
See https://bugzilla.redhat.com/show_bug.cgi?id=632391
 
I use 'du -k' command to find out which directory took space. I use 'rm' command to delete the contents.


Even I delete the content, the directory still grows up daily.
== chkservice ==
[https://www.linuxuprising.com/2019/11/chkservice-is-systemd-units-manager.html chkservice] Is A systemd Unit Manager With A Terminal User Interface


=== Upgrade Python from 2.6.x to 2.7.x ===
= Kernel =
[http://bicofino.io/blog/2014/01/16/installing-python-2-dot-7-6-on-centos-6-dot-5/ This instruction] tells how to install Python 2.7 from source.
* [https://opensource.com/article/19/8/linux-kernel-21st-century How to compile a Linux kernel in the 21st century]
<pre>
* [https://www.ostechnix.com/different-ways-to-update-linux-kernel-for-ubuntu/ Different Ways To Update Linux Kernel For Ubuntu]
yum -y update
yum groupinstall -y 'development tools'
yum install -y zlib-devel bzip2-devel openssl-devel xz-libs wget
wget http://www.python.org/ftp/python/2.7.8/Python-2.7.8.tar.xz
xz -d Python-2.7.8.tar.xz
tar -xvf Python-2.7.8.tar


# Enter the directory:
= Firmware update =
cd Python-2.7.8
[https://9to5linux.com/fwupd-1-9-9-released-with-support-for-lenovo-x1-yoga-gen7-530e-2-in-1-laptops Fwupd 1.9.9 Released with Support for Lenovo X1 Yoga Gen7 530E 2-in-1 Laptops]


# Run the configure:
= Game =
./configure --prefix=/usr/local
See [[Game|Game]].
 
# compile and install it:
make
make altinstall
 
# Checking Python version:
[root@nicetry ~]# python2.7 -V
Python 2.7.8
 
wget --no-check-certificate https://pypi.python.org/packages/source/s/setuptools/setuptools-1.4.2.tar.gz
 
# Extract the files:
tar -xvf setuptools-1.4.2.tar.gz
cd setuptools-1.4.2
 
# Install setuptools using the Python 2.7.8:
python2.7 setup.py install
curl https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py | python2.7 -
pip2.7 install virtualenv
</pre>
 
=== Install Meld ===
Have not found a solution yet. We need to install it from source. However, the source depends on
* Python 2.7 (see above for the instruction)
* GTK+ 3.6
* GLib 2.34
* PyGObject 3.8
* GtkSourceView 3.6
 
(Update) A binary version of meld is already available in the git. See [http://linuxg.net/how-to-install-meld-3-11-2-on-ubuntu-linux-mint-debian-fedora-opensuse-mageia-and-their-derivative-systems/ this post].
<pre>
$ cd ~/Downloads/
$ git clone https://git.gnome.org/browse/meld
$ cd meld
$ sudo ln -s /home/$USER/Downloads/meld/bin/meld /usr/bin/meld
</pre>
 
=== VirtualBox guest addition ===
Check out [http://www.if-not-true-then-false.com/2010/install-virtualbox-guest-additions-on-fedora-centos-red-hat-rhel/ this post].
<pre>
su
# click VirtualBox -> Devices -> Install guest addition
mkdir /media/VirtualBoxGuestAdditions
mount -r /dev/cdrom /media/VirtualBoxGuestAdditions
rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
yum install gcc kernel-devel kernel-headers dkms make bzip2 perl
KERN_DIR=/usr/src/kernels/`uname -r`
export KERN_DIR
cd /media/VirtualBoxGuestAdditions
./VBoxLinuxAdditions.run
</pre>
(Update for 64-bit CentOS 6.5 + VirtualBox 4.3.18) The installation still failed and it showed a missing package which can be installed with
<pre>
yum install kernel-devel-2.6.32-431.el6.x86_64
</pre>
Then I re-run ./VBoxLinuxAdditions.run to finish the installation of guest addition. Reboot and GA works.


=== [http://rockstor.com/ Rockstor Linux] ===
= Best Linux Adobe Alternatives You Need to Know =
Build and manage your own Linux & BTRFS powered advanced NAS and Cloud storage with ease
* https://linux.cn/article-8928-1.html and https://www.maketecheasier.com/adobe-alternatives-for-linux/


# Personal Cloud Server
= Linux distributions =
# SMB Cloud Server
[[Linux_Distribution|Linux Distribution]]
# Traditional NAS server


== Online Tools ==
= chroot =
* Non-boring presentation: [http://prezi.com/ Prezi]. Also funny comics can be found from [http://xkcd.com/ xkcd.com].
[[Chroot|Chroot]]
* Flow chart/Mind-mapping: [https://www.mindmup.com/#m:new MindMup], [https://www.lucidchart.com/ LucidChart]
* Image editor: [http://pixlr.com/editor/ Pixlr Editor] (vs [http://askubuntu.com/questions/164473/simple-image-editor Pinta or Shotwell] in Ubuntu)
* Video editor: [https://www.wevideo.com/ WeVideo] (vs [[#Edit_a_video_using_OpenShot|OpenShot]] in Ubuntu)
* Virus : [https://www.virustotal.com/en/ Virus Total]
* Finance: [https://www.mint.com/ Mint]

Latest revision as of 16:09, 3 November 2024

man

Navigation

Gentoo and fossbytes

  • Enter – Move down one line
  • Space – Move down one page
  • g – Move to the top of the page
  • G – Move to the bottom of the page
  • q – Quit

Search within a man page

Use / and type your search pattern.

Use 'n' for forward search and 'N' for reverse search.

The matched line will be moved to the top of the screen.

By default, the search is case insensitive or we can use man -i COMMAND.

Regular expression is supported. For example to find all of the long arguments with: /(--)[a-Z]

Colored man pages

This is a cool tip!

By default, the man program normally uses a terminal pager program such as less to format its output.

Add the following to "~/.bashrc" file. For example, LESS_TERMCAP_mb customizes the appearance of blink text in the less pager (or man command) and LESS_TERMCAP_us customizes the appearance of underlined text in the less pager.

# Customize less colors
export LESS_TERMCAP_mb=$'\e[1;32m'  # Blinking text: bold green
export LESS_TERMCAP_md=$'\e[1;34m'  # Bold text: bold blue
export LESS_TERMCAP_me=$'\e[0m'     # End mode
export LESS_TERMCAP_so=$'\e[01;47;34m'  # Standout: bold white on blue
export LESS_TERMCAP_se=$'\e[0m'     # End standout mode
export LESS_TERMCAP_us=$'\e[1;4;31m'  # Underlined text: bold underlined red
export LESS_TERMCAP_ue=$'\e[0m'     # End underline

(New way, The most Pager) How To Display Color Man Pages in Linux and Unix or How to Display man Pages in Color on Linux.

Navigate to another man page within a man page

See here.

When inside the man page, press ! followed by a valid shell command.

For example : !man cat

View a specific "Section"

$ whatis printf
printf (1)           - format and print data
printf (3)           - formatted output conversion
Printf (3o)          - Formatted output functions.
$ man 3 printf

Read man pages in vi without using temporary files

What is a way to read man pages in vim without using temporary files

man find | vi -

Search man page referenced by

man -f KEYWORD

This command is equivalent to whatis -r KEYWORD

Search from all man pages

man -k KEYWORD will give you a list of all man pages which relate to 'KEYWORD'.

TLDR pages/cheat sheet: alternative to Man

Cheat.sh (better than TLDR)

Cheat.sh Shows Cheat Sheets On The Command Line Or In Your Code Editor. There are different ways to use it. One way does not require to install anything as long as we have the curl command.

curl cheat.sh/tar

curl cht.sh/python/random+list # Python programming language cheat sheet for random list

My test shows cheat.sh can find more commands and it gives colored output.

Some books

Beautiful desktop

.desktop file

This is not related to beautiful desktop. It is used to launch applications in Linux. Without the .desktop file, your application won’t show up in the Applications menu and you can’t launch it with third-party launchers such as Synapse and Albert Launcher.

The .desktop files are commonly saved in

  • ~/local/share/applications
  • /usr/share/applications

List of installed desktop environment

ls -l /usr/share/xsessions/

Themes

5 of the Best Linux Dark Themes that Are Easy on the Eyes

Virtual consoles/virtual terminals

Linux allows virtual consoles (aka virtual terminals) to be opened while an X Window System is executing.

Use Ctrl + Alt + FX to open a virtual console-- there are six virtual text-based consoles (F1 to F6). Use Alt + F7 (or possibly other keybinds) to return to the X Window System.

Managing devices in Linux -> Fun with device files.

Change/increase console fonts

Desktops/Workspaces

Ctrl + Alt + -> or Ctrl + Alt + <- to switch workspaces.

Ctrl + Alt + down can list the open applications on the current workspace.

Ctrl + Alt + up can show all workspaces and the open applications. We can use mouse to move an app to any workspace.

SuperKey + left tile a window to left. SuperKey + right tile a window to right.

Complete List of Linux Mint 18 Keyboard Shortcuts for Cinnamon for more examples.

Mouse

How To Bind Mouse Buttons To Keyboard Keys Or Commands (Linux Using X11)

Virtual memory

vmstat

hcache

A tool fork from pcstat, with a feature that showing top X biggest cache files globally

Memory: free command

Three types of memory reported by the free command.

  • Used: RAM that is currently in use by an application.
  • Available: RAM that may be in use for disk caching but can be freed up for applications. What is 'available' vs 'free' memory in free command?. Available = Estimation of how much memory is available for starting new applications, without swapping.
  • Shared: Amount of memory used by the tmpfs file systems.
  • Free: RAM that is not in use by an application or disk caching.
  • Total = Used + Free + Buffers/Cache

How to Clear RAM Memory Cache and Buffer

# To clear pagecache, enter the following command:
echo 1 > /proc/sys/vm/drop_caches

# To clear dentries and inodes, change the number to 2:
echo 2 > /proc/sys/vm/drop_caches

# To clear pagecache, dentries, and inodes all together, change the number to 3:
echo 3 > /proc/sys/vm/drop_caches

How do I determine the number of RAM slots in use

sudo dmidecode -t memory

Logging memory

Shows Per-Program Memory Usage On Linux

$ pip install ps_mem
$ ps_mem -p $(pgrep -d, -u $USER)
 Private  +   Shared  =  RAM used	Program
...
249.9 MiB +  43.9 MiB = 293.9 MiB	firefox
549.7 MiB +  82.2 MiB = 631.9 MiB	Web Content (6)
  1.0 GiB + 149.6 MiB =   1.2 GiB	chrome (16)

3.2 GiB

Check RAM information

sudo dmidecode -t memory

sudo dmidecode -t 17

Free up memory

Monitor Memory Utilization And Send an Email

zram

rop swap for zram on Linux

Things to do after a fresh install of GNU/Linux

  1. Run upgrade such as apt-get update; apt-get upgrade. It helps to resolve the unmet dependencies issue too.
  2. Increase audio quality
  3. Make sure firewall is enabled.
  4. Disable any unnecessary services
  5. Install Timeshift
  6. Install ClamAV / Clamtk antivirus

Query whether the OS is 64-bit or 32-bit

SYSTEM_ARCH=getconf LONG_BIT
echo $SYSTEM_ARCH

Command line improved

https://remysharp.com/2018/08/23/cli-improved

Directory permission / attribute

See http://unix.stackexchange.com/questions/21251/how-do-directory-permissions-in-linux-work

When applying permissions to directories on Linux, the permission bits have different meanings than on regular files.

  • The write bit allows the affected user to create, rename, or delete files within the directory, and modify the directory's attributes
  • The read bit allows the affected user to list the files within the directory
  • The execute bit allows the affected user to enter the directory, and access files and directories inside

When we create a new directory, the attribute is 775. Some pre-created directories (Desktop, Documents, Music, Pictures, Public) have an attribute 755.

Making a new temporary directory

https://www.howtoforge.com/linux-mktemp-command/

mktemp  # temp directory is under /tmp
mktemp -d tempdirXXX # temp directory is under the current directory
mktemp tempfileXXX # temp file under the current directory

Shell

Login shell and non-login shell

Login Shell

  1. /etc/profile
  2. /etc/profile.d/*.sh
  3. ~/.bash_profile or ~/.profile (for example, environment variable like PATH)
  4. ~/.bashrc
  5. /etc/bashrc
  6. ~/.bashrc

Non-Login shell

  1. ~/.bashrc
  2. /etc/bash.bashrc or /etc/bashrc
  3. ~/.bashrc (bash-related settings, for example, prompt string, aliases)

Note: Bash only reads the first of the files in ~/ that it finds (and ignore the rest). rc means run commands for example, .nanorc.

Aliases and Functions for Individual Users

  1. /etc/profile (systemwide environment and shell variables)
  2. /etc/profile.d/*.sh (systemwide environment and shell variables)
  3. ~/.bash_profile (user environment and shell variables)
  4. ~/.bashrc (executes /etc/bashrc)
  5. /etc/bashrc (systemwide aliases and shell functions)
  6. ~/.bashrc (user aliases and shell functions)

Why does it take tens of seconds to get a shell prompt?

https://serverfault.com/a/722496 If your profile or bashrc have expensive things, consider trimming them back.

On raspbian commenting out some lines does help. Interestingly, the same lines does not make any difference on x86 server.

the source command

The . is a shorthand for the source command in bash. source ~/.bashrc and . ~/.bashrc are equivalent.

login shell (.bash_profile) vs interactive shell (.bashrc)

  1. login shell - non desktop environment. ~/.bash_profile is sourced for the bash shell. It is the shell you get when logging in or opening a new terminal session.
  2. interactive shell - Ctrl+Alt+t to open a terminal from a graphical mode (desktop environment) and also the ssh connection. ~/.bashrc is source. We usually edit ~/.bashrc to set up the environment to include fancy prompt, set aliases, set history options, or define custom shell functions. Bash Check If Shell Is Interactive or Not Under Linux / Unix Oses
  3. Non-interactive shell - instances of the shell you can't use interactively. Shells that are started to run a command or script.

To determine the shell type: echo $-

export environment variables

  1. Both a login shell and an interactive one. SSH (Putty) to connect to a remote machine.
  2. When a shell runs a script or a command passed on its command line, it's a non-interactive, non-login shell.

/root/.bashrc

If we use "sudo SOME_COMMAND", ~/.bashrc won't work. In this case, we have to

  1. run "sudo su"
  2. Edit /root/.bashrc

Login banner

How to configure login banners in Linux (RedHat, Ubuntu, CentOS, Fedora). /etc/motd and /etc/login.warn

Change to root shell

The following command will switch to an environment similar to what the user would expect had the user logged in directly.

sudo su -
# OR
sudo su
# OR
sudo -s

This can be useful when running 'su' or 'su -' failed because of an authentication failure error (note Ubuntu locked the root account).

See also

For sudo to work, my account ('debian' in this case) has to be included in the config file /etc/sudoers.

debian  ALL=NOPASSWD: ALL

When sudo is invoked, it asks for the password of the user who started it.

pinky: find out about the people logged on to your Linux computer

How to Use the pinky Command on Linux

su: Switch to another user and run a command

  • su means 'substitute user'.
  • Use
    su newusername   # keeps the environment variables of the original user
    su - newusername # clears all the environment variables
    
  • Linux Run Command As Another User runuser -l command
    runuser -l  userNameHere -c 'command'
    

Keyboard shortcut to move cursor in the terminal

  • Alt + b: go left (back) one word
  • Alt + f: go forward on word

Example: cd ~/bitbucket/gbmpdx/annovar_biowulf (Now press Alt+b to see the cursor moves)

Record terminal session to a text file

script history_log.txt
# recording begins
exit # stop recording

This will include everything showing on your screen.

Tools To Record Your Terminal And Generate Animated Gif or SVG Images

Asciinema & agg

$ # sudo pip3 install asciinema  # Error
$ # sudo apt install python3-asciinema # Error
$ sudo apt install pipx
$ pipx ensurepath
Success! Added /home/brb/.local/bin to the PATH environment variable.

Consider adding shell completions for pipx. Run 'pipx completions' for
instructions.

You will need to open a new terminal or re-login for the PATH changes to take
effect.

Otherwise pipx is ready to go! 

Open another tab

pipx install asciinema
asciinema rec 2g-test
asciinema play 2g-test
chmod +x Downloads/agg-x86_64-unknown-linux-gnu 
Downloads/agg-x86_64-unknown-linux-gnu 2g-test 2g-test.gif
open 2g-test.gif

terminalizer

sudo apt update
sudo apt install nodejs npm
sudo npm install -g npm
sudo npm install -g terminalizer
terminalizer record demo
terminalizer play demo
terminalizer render demo 
# https://github.com/faressoft/terminalizer/issues/29
# https://github.com/faressoft/terminalizer/issues/211

Termtosvg

(archived) Termtosvg – Record Your Terminal Sessions As SVG Animations In Linux

Record and Replay Linux Terminal Sessions Activity: script

Learn how to Record and Replay Linux Terminal Sessions Activity

Recording your terminal: asciinema

https://asciinema.org/

Clear screen

ctrl + l

Clear text

ctrl + u: "deletes" all the entered text to the left of the cursor. Does not work in macOS shell but R console from RStudio in macOS still works.

Redirect standard error

http://bash.cyberciti.biz/guide/Standard_error. Use 2> operator.

command 2> errors.txt

Redirect standard output

This can be used in the cron job or displaying a clock on the desktop.

$ cat ~/bin/clock
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139   &>/dev/null &

Quotes and asterisk

Combining these two will not work. For example

brb@T3600 ~ $ ls -l ~/GSE48215/*.fastq
-rw-r--r-- 1 brb brb 16226673016 Jun 14 14:13 /home/brb/GSE48215/SRR925751_1.fastq
-rw-r--r-- 1 brb brb 16226673016 Jun 14 14:13 /home/brb/GSE48215/SRR925751_2.fastq
brb@T3600 ~ $ ls -l '~/GSE48215/*.fastq'
ls: cannot access ~/GSE48215/*.fastq: No such file or directory
brb@T3600 ~ $ ls -l "~/GSE48215/*.fastq"
ls: cannot access ~/GSE48215/*.fastq: No such file or directory

cat command alternatives

$ curl -s  https://api.github.com/repos/sharkdp/bat/releases/latest |grep browser_download_url |  cut -d '"' -f 4 | grep 'amd64.deb' | grep -v musl | wget -i -
$ sudo dpkg -i bat_*_amd64.deb

ls command

List Files With Detailed Information from How to Use the ls Command in Linux

To use UID/GID instead of the user name and group name in ls -l, use the -n option.

ls -n

To make a pretty output by showing selected columns (col 9 is the file name and col 5 is the file size)

$ ls -nt bad |  grep -v ^total | awk '{ printf  "%-20s %15i\n", $9, $5}'
recal.bai                    8069704
recal.bam                12275091222
recal_data.table             1012453
realigned_reads.bai          8065496

Follow the symbolic link

Use -H option

ls -lH myDir

List only directories

ls -d */               # current directory
ls -ld ~/Downloads/*/  # ~/Downloads
ls -l -d */

List only files

ls -l | egrep -v '^d'

Find and Delete Broken Symbolic Links

find /path/to/directory -xtype l -delete

Special characters, escape

List of characters which needs to be escaped in a linux shell command

|  &  ;  <  >  (  )  $  `  \  "  '  <space>  <tab>  <newline>

Opened MS-Office documents' filenames start with "~$". The dollar sign character has to be escaped; eg ls -l ~\$* to list these kind of files or rm ~\$* to delete these files.

Check non-English characters

How to Find Non-ASCII Characters in Text Files in Linux

perl -ne 'print if /[^[:ascii:]]/' sample.txt

ls | more without lose color

$ ls --color=auto
$ ls --color | more

Most likely your ls is aliased to ls --color=auto. If you do ls --color (which is morally equivalent to ls --color=always), that will force it to turn on colors.

ls directories color

How to Change the Colors of Directories and Files in the ls Command. No need to use the export command when we want to add it to .bashrc file.

# orange color
export LS_COLORS=$LS_COLORS:'di=0;33:'
# OR yellow color if your terminal supports 256 colors
export LS_COLORS=$LS_COLORS:'di=38;5;226:'

ls output with color background

stackexchange or askubuntu.

In my case, after I apply chmod 755 -R XXXX, the weird green background color goes away.

ls output without user/group columns

https://unix.stackexchange.com/a/205165

ls -lhog

To further skip the first 2 columns (the permissions and link count) we can use

ls -lhog | sed 's/^[^ ][^ ]*  *[^ ][^ ]* //'
# total 95G
#  51G May  7 11:37 SRR10156301_3.fastq  --> file
#  23G May  7 11:35 SRR10156301_2.fastq  --> file
#  18G May  7 11:35 SRR10156301_1.fastq  --> file
# 4.0K May  7 11:24 SRR10156301          --> directory

ls output selected columns

The following example will sort the output by file size and output only the file size and file name columns.

ls -lS  . | awk '{print $5 "\t" $9}'

ls -lhS  . | awk '{print $5 "\t" $9}'

# Mac
ls -lS  *.Rmd |head | awk '{print $6 "\t" $10}'
# a range of columns:
ls -lS  *.Rmd |head | awk -v f=6 -v t=10 \
    '{for(i=f;i<=t;i++) printf("%s%s",$i,(i==t)?"\n":OFS)}'

ls suddenly wrapping items with spaces in single quotes

Use ls -N to remove single quotes for files containing spaces. See Why is 'ls' suddenly wrapping items with spaces in single quotes?

Better to add export QUOTING_STYLE=literal to .bashrc

ls on BSD/macOS

Use the -G option to get a color output

$ ls -G

realpath

realpath FILENAME to get the full path of a file.

tree command

tree -d: show directories only

tre command

  • github. Binary files for x86 and arm linux are available. To use it, run "tre DIRECTORYNAME" or "tre" to list files recursively from the current directory.

cp command

Linux cp command tutorial for beginners (8 examples)

copy a directory

cp -avr Dir1 Dir2

where -a will preserve the attributes of files/directories, -v means verbally and -r means copy the directory recursively.

Copy a file with progress bar with pv (plus how to eject the USB drive)

http://www.tecmint.com/monitor-copy-backup-tar-progress-in-linux-using-pv-command/

sudo apt-get install pv
pv file1 > file2    # don't forget the ">" operator and the destination is a file, not a directory

After that, instead of clicking the reject icon from the file manager to eject it, it is better to use a command line to do that because there is no expect time for users to know when it will take for finish writing the data to a USB drive.

sudo apt-get install udisks

sudo udisks --unmount /dev/sdb1   # /dev/sdb1 is the partition
sudo udisks --detach /dev/sdb     # /dev/sdb is the device

My testing shows this procedure works (tested by running md5sum after eject/plug-in) when I need to copy a 9GB file.

Reliable way: Split the large file and copy smaller chunks

# Use 'sudo iotop -o' to monitor the I/O
split -b 4G inputFile  # create xaa, xab, ... files
cat x* > outputFile    # merge them. md5sum check succeeds

type  x* > outputFile  # Windows OS. # https://stackoverflow.com/a/60254

# Use Prefix, and use numeric suffixes starting from 0
split -b 4M -d inputFile inputFile.part
md5sum inputFile
cat inputFile.part* > inputFile2
ech "LONG_MD5_SUM_From_inputFile inputFile2" | md5sum -c

It is interesting copying smaller files (eg 4GB) to USB drives is quite stable (just use the cp command). Even for a not-too large file (6.7GB), pv step looks OK but the unmount/detach step failed.

For a 6.7GB file, it will split it into a 4GB and 2.7GB files. Merge takes longer time if it is done on the USB drive. That is, it is best to do merge in the final destination (internal disk/storage).

  • split in the internal hdd: 1min 38sec
  • merge in the internal hdd: 37sec
  • merge in the USB 3.0 drive: 2min 17sec

Remember: Use a reliable USB drives.

The operation could not be completed because the volume is dirty

On a USB 2.0 drive, I can copy files to there but the drive cannot be rejected (Ubuntu has a pop-up showing it is still writing data to it).

When I forcibly rejects the drive and plug it in a Windows PC, Windows shows the message The operation could not be completed because the volume is dirty. This gives a way to run chkdsk (check and repair a file system).

  1. Open a Windows File Manager
  2. Right click the USB drive
  3. Properties
  4. Tools -> Check now... Start

Done. Now I can use the drive again.

The Linux equivalent to chkdsk is fsck. fsck is a front end that calls the appropriate tool (fsck.ex2, fsck.ex3, e2fsck, ...) for the filesystem in question.

umount /dev/sdb1        # thumb drive
sudo fsck /dev/sdb1

sudo fsck -a /dev/sdb1  # auto repair

For the root disk, you have to use a live CD. Otherwise, you will see a message like

$ fsck /dev/sdb1
fsck from util-linux 2.20.1
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdb1 is mounted.

WARNING!!!  The filesystem is mounted.   If you continue you ***WILL***
cause ***SEVERE*** filesystem damage.

Do you really want to continue<n>? no

Files

List files by sorting according to the file size

Use the -S option in ls.

List files using wildcard without showing files under subdirectories

Use the -d option in ls. For example, the following command will not showing files under R-3.4.4 and R-3.5.3

$ ls -d R*
drwxr-xr-x 15 brb brb     4096 Mar 14 09:48 R-3.4.4
-rw-rw-r--  1 brb brb 30474612 Mar 15  2018 R-3.4.4.tar.gz
drwxr-xr-x 15 brb brb     4096 Mar 14 09:31 R-3.5.3
-rw-rw-r--  1 brb brb 30205979 Mar 11 04:04 R-3.5.3.tar.gz

Delete multiple files

How to Remove Multiple Subdirectories with One Linux Command

rm -r ~/Documents/htg/{done,ideas,notes}

Delete a certain type of files recursively under a directory

For example to delete *.o files under the current directory,

find . -type f -name '*.o' -delete

Remove all files/directories except for one file/some file type

https://unix.stackexchange.com/a/153863

# recursively, including hidden ones
find . ! -name 'file.txt' -type f -exec rm -f {} +

# Non-recursively
find . -maxdepth 1 ! -name 'file.txt' -type f -exec rm -f {} +

find: warning: you have specified the -maxdepth option after a non-option argument !, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it). Please specify options before other arguments.

Remove all hidden files/directories

Bash Find And Delete All Hidden Files Directories

rm -rf .??*  # tested, http://labtestproject.com/linuxcmd/rm.html

# list all hidden files/directories
find . -name ".*" -print

# delete all hidden files
find . -name ".*" -type f -delete

find . -name ".DS_Store" -delete

Create a new directory and cd to it

How to Make a New Directory and Change to It with a Single Command in Linux

Set permissions for new files or directories

  • umask: user file-creation mode mask
  • With umask 007, newly created files and directories will have all permissions (read, write, and execute) for the user and the group, but no permissions for others. This is a good practice when you want to share data with other users in the same group but want to completely exclude users who are not group members.
  • Set up default umask on Linux: adding the command umask 007 to the .bashrc file sets the default umask value for your shell. This means that every time you start a new shell session, the umask will be set to 007.
  • How it works:
    • The default permissions for files are 666 (read and write for owner, group, and others) and for directories are 777 (read, write, and execute for owner, group, and others).
    • The default permissions for files are 666 and for directories are 777. In binary, these are 110 110 110 and 111 111 111 respectively. The umask value 007 is 000 000 111 in binary.
    • The AND operation is performed between the binary representations of the default permissions and the bitwise NOT of the umask value. That is, the mask is negated (its bitwise compliment is taken) and this value is then applied to the default permissions using a logical AND operation.
    • The result of the AND operation is 110 110 000 for files and 111 111 000 for directories. In decimal, these are 660 and 770 respectively.
  • See What is Umask and How To Setup Default umask Under Linux?, Linux umask command.

chown and chmod recursively (-R)

Use -R (capital R).

chmod -R u=rwx,go=rx /var/www/html

Note it is better not to remove 'x' on folders. Otherwise we will lose the permission to change file attributes for any file under the folder.

Note "chmod -R ugo+rwx XXX" is the same as "chmod -R 777 XXX" b/c "u" stands for user, "g" stands for group and "o" stands for others.

Get the chmod numerical value for a file/directory

https://unix.stackexchange.com/a/46921

# BSD/OS X: 
stat -f "%OLp" <file>

# Linux: 
stat --format '%a' <file>
stat -c %a <file>

After that we can use ls -lhog to verify.

Files under a directory have question mark attribute

Use sudo chmod -R a+x /some/directory to fix. This happened when I unzip a zip file compressed in a Windows OS.

Files have an integer owner in attributes

What does the “number” in the owner field of files signify in linux?

You probably did a copy that preserved the original group and owner of these files. Within linux internally the owner and group is basically just an id.

You can change the ower and group to an existing owner and group with the commands chown and chgrp respectively.

Uppercase S in permissions of a folder and setGID

I happen to create this case by chmod -R 760 ShareFolder. To make 'S' to become 's', I just need to use chmod -R 2770 ShareFolder.

immutable files

Manage file and directory attributes using chattr and lsattr command

Display files sorted by modified date in a directory recursively

stat --printf="%y %n\n" $(ls -tr $(find DIRNAME -type f))
find -type f -printf '%T+\t%p\n' | sort -n

Both of methods give the same output. Note the latest changed file is shown at the bottom of the output.

Sort files by their size

use the '-S' option.

ls -lS

Files starting with a dash (meta-characters)

Move File Starting With A Dash

$ > '-foo.txt'
$ rm "-foo.txt"
rm: invalid option -- 'o'
Try 'rm ./-foo.txt' to remove the file '-foo.txt'.
Try 'rm --help' for more information.
$ rm -- -foo.txt

Inodes

Recover Deleted Files

How to Recover Deleted Files on Linux

alias

https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/

$ alias # list all aliases
$ alias | grep ls
$ unalias ls
$ alias ls='ls --color=auto' # save it in ~/.bash_profile or ~/.bashrc
$ alias server_name="ssh -v -l john 192.168.1.11" # or modify /etc/hosts
$ alias open='xdg-open'
$ alias sshnocheck='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias scpnocheck='scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias sshserver='ssh [email protected]'
$ alias checkport='sudo lsof -i -P -n | grep LISTEN'

NOTE the last column of the output from "checkport" will show who can connection to the port. For example, if it shows "127.0.0.1:10999 (LISTEN)", it means only the server can connect to port 10999. If it shows "*:22 (LISTEN)", it means any machines can connect to the server through port 22.

To avoid using the alias, use one of the following ways (eg use the command's full path)

$ \ls
$ /bin/ls
$ command ls
$ 'ls'

Useful aliases (Added to ~/.bashrc)

alias nano="nano -c --softwrap"

We can use the backslash to escape the double quote (or others like dollar sign).

If a command needs the sudo right, include the command inside alias. In the following example, if we skip "sudo" then running the command "sudo lsof2" will result in an error: sudo: lsof2: command not found.

alias lsof2="sudo lsof -i -P | egrep \"PID|LISTEN\""

Use unalias [alias name] to remove an alias.

Find file defining an alias

how to find file defining an alias. It works on macOS. Many of them are defined in ~/.oh-my-zsh/lib/directories.zsh. Another way (without saving) is How to find out where alias (in the bash sense) is defined when running Terminal in Mac OS X.

lolcat - bring color to text

sudo apt-get install ruby	
sudo gem install lolcat
lolcat -h
lolcat --version
fortune | lolcat

ps | lolcat
man ls | lolcat

lolcat test.R

sudo apt install figlet
figlet Merry Christmas | lolcat

alias lolls="ls -l | lolcat"
lolls

File manager

Cloud commander

diff

Run diff with large files

diff (or even better the cmp command) works fine with 8G fastq files. Note cmp compare files byte by byte so it probably won't run out of memory. How to diff large files on Linux.

Another strategy is to split a large file into small pieces. For example,

split -b 500MB FILEname # into 500MB files each
split -l 200 FILEname   # into smaller files with 200 lines each

Meld freezes When I tested it with two large files (800k & 936k lines coming from human gtf files). Actually the whole linux system became unresponsive.

Actually Meld is sluggish when it is used in small files in Odroid XU4 running Ubuntu 16.04 MATE. I have used Meld 3.14.2 and the latest 3.16.2.

Kompare

https://apps.kde.org/en/kompare

Meld cannot change theme. So if my desktop has a dark theme, meld is hard to read.

Kompare still has a light them.

Directory

diff -qr dir1 dir2

where -q means to report only when files differ and -r is to recursively compare any subdirectories found.

diff & colordiff-color on terminal: compare side by side

PS. For a GUI version of diff, Meld works fine. Need to install first. apt-get install colordiff. http://www.cyberciti.biz/programming/color-terminal-highlighter-for-diff-files/

sudo apt-get install colordiff
diff -y file1 file2 | colordiff
# Ignore same rows (two ways):
# diff -C0 file1 file2 | colordiff
# diff -U0 file1 file2 | colordiff

# On systems that I have no root right, I need to install it from the source 
# (just need to run 'make')
$ diff file1 file2 | ~/bin/colordiff-1.0.18/colordiff.pl

where -y option means to show the output in two columns.

Colordiff.png

Interpretation of the diff output:

The first line of the diff output will contain:

  • line numbers corresponding to the first file,
  • a letter (a for add, c for change, or d for delete), and
  • line numbers corresponding to the second file.

In our output above, 2,4c2,4 means: "Lines 2 through 4 in the first file need to be changed in order to match lines 2 through 4 in the second file." It then tells us what those lines are in each file:

  • Lines preceded by a < are lines from the first file (color in red);
  • lines preceded by > are lines from the second file (color in green).
  • The three dashes ("---") merely separate the lines of file 1 and file 2.
2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed.
---
> I need to do the laundry.
> I need to wash the car.
> I need to get the dog detailed.
colordiff -ur path1 path2

If you change -ur to -urN then that will also show the contents of files that are only present in one of the paths. Colordiff2.png

The meaning of colors can be found in /etc/colordiffrc (man colordiff or colordiff web site)

  • plain=off
  • newtext=darkgreen
  • oldtext=darkred
  • diffstuff=darkcyan
  • cvsstuff=cyan

git diff --no-index -- file.a file.b

Any visual diff in Linux console?

gnome-terminal

Remember the session

The following is proved working on Ubuntu 18.04

gnome-terminal --tab --working-directory=$HOME/Downloads \
               --tab --working-directory=$HOME/Documents

Fun: piano

Let Us Play Piano In Terminal Using Our PC Keyboard

Terminals in grids

See Terminal_multiplexer.

Tilix

Terminator

GNU screen

tmux*

Byobu

Guake / Yakuake / Tilda

Drop down terminals for the GNOME / KDE / GTK Environments. Great for quick access to a terminal!

System date/time, ntpd

$ timedatectl
      Local time: Mon 2019-06-10 08:37:09 EDT
  Universal time: Mon 2019-06-10 12:37:09 UTC
        RTC time: Mon 2019-06-10 12:37:09
       Time zone: America/New_York (EDT, -0400)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

Linux file timestamps

Linux File Timestamps Explained: atime, mtime, and ctime

Change the date/timestamp of a file - touch

Modify the file relative to its existing modification time

filename=MyFileName
touch -d "$(date -R -r $filename) - 2 hours" $filename # 2 hours before
touch -d "$(date -R -r $filename) + 2 hours" $filename # 2 hours later

See How can I change the date modified/created of a file?

Find binary file location, type

  • which - Display the full path of shell commands. See examples from cyberciti.biz.
$ which ls
/bin/ls
  • whereis - locate the binary, source, and manual page files for a command. See examples from cyberciti.biz.
$ whereis ls
ls: /bin/ls /usr/share/man/man1p/ls.1p.gz /usr/share/man/man1/ls.1.gz
$ type ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
  • locate. Use locate command mindfully. It is used to find the location of files and directories. Note that locate does not search the files on disk rather it searches for file paths in a database. For example, the following command will search .png files over the system (not only the personal directory).
locate "*.png" 
See How to use updatedb command as an ordinary user?, Use updatedb and locate to index files.

find: Find a file

find operates recursively into sub folders.

-iname

Search by a file name

$ find . -type f -name "abc*" # find a file starting with abc
$ find . -iname '*.txt'  # -iname or -name is necessary

It also works for searching files on subdirectories.

$ find . -name transcripts.gtf
./RH_bio/transcripts.gtf
./dT_ori/transcripts.gtf
./dT_tech/transcripts.gtf
./dT_bio/transcripts.gtf
./RH_ori/transcripts.gtf
./RH_tech/transcripts.gtf

-mtime, -ctime, -atime argument

Find files modified in 10 days.

$ find . -ctime -10 # include subdirectories
.
./mediawiki-1.32.0.tar.gz
./d
./d/deepSurv.pdf

Find files modified in one day and contain string 'est'

$ find . -mtime -1 -exec grep --with-filename est {} \;

If the search directory is not the current directory, we need to add a forward slash to the directory name.

$ find ~/Desktop -iname '*.txt'  # Not working
$ find ~/Desktop/ -iname '*.txt' # Working 

The following example shows we can list multiple search criteria. The “‑r” option in tar appends files to an archive. xargs is a handy utility that converts a stream of input (in this case the output of find) into command line arguments for the supplied command (in this case tar, used to create a backup archive).

find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar

What is the difference between mtime, atime and ctime?

  • mtime (modification time) indicates the time the contents of the file has been changed. Mind you, only the contents. Not the attributes.
  • ctime (change time) is the timestamp of a file that indicates the time that it was changed. Now, the modification can be in terms of its content or in terms of its attributes.
  • atime (access time) is the timestamp that indicates the time that a file has been accessed.

xargs

See Linux Programming

-exec COMMAND {} \;

  • Search and list files with details
    find . -type f -name "*street*" -exec ls -lh {} \;

    -exec ls -lh {} \; executes the ls -lh command on each found file. The {} is a placeholder for the current file, and \; indicates the end of the -exec command.

  • How to run find -exec?, Using semicolon (;) vs plus (+) with exec in find
    # This command will run grep chrome on each file individually.
    find . -exec grep chrome {} \;
    
    # This command will run grep chrome on batches of files, reducing the number of times the command is executed.
    # Using + can significantly improve performance
    find . -exec grep chrome {} +
    

    Note:

    • The backslash before ; is to escape ; so linux won't interpret it directly.
    • Command Compatibility: Not all commands support being executed with multiple arguments at once. For example, grep can handle multiple files, but some other commands might not. In other words, while -exec COMMAND {} + can be more efficient, it’s important to ensure the command you’re using supports this usage and behaves as expected.
  • Find files and execute something (google: find --exec)
    $ find ./ -name "*.tar.gz" -exec tar zxvf {} \;
    
  • Find and move files to a new directory
    find OLDDIR -type f -exec mv -t NEWDIR {} + 
    
  • Find the total file size of a list of files.
  • What is meaning of {} + in find's -exec command?
  • Why does 'find -exec cmd {} +' need to end in '{} +'?
  • How to run find -exec? The following will find out the total file size of the 'accepted_hits.bam' file under all sub-directories.
    find ./ -iname "accepted_hits*" -exec du -ch {} + | grep total$
    

    where '-c' produces a grand total, and will substitute {} with the filename(s) found in -exec.

How to find and delete directory recursively

How to find and delete directory recursively on Linux or Unix-like system. Application: recursively remove backups older than 30 days.

Find all soft link files

find /tmp -type l

Recursive statistics on file types in directory?

You could use find and uniq for this. This is fast!

$ find . -type f | sed 's/.*\.//' | sort | uniq -c

Exclude or Ignore Files

Find command Exclude or Ignore Files (e.g. Ignore All Hidden .dot Files )

Avoid Permission Denied Messages

How to fix find command permission denied messages

  • Redirecting ALL standard error (not only permission denied error): 2>/dev/null.
find . -iname "data*.txt" -print 2>/dev/null
  • Focus on the 'permission denied' message: grep -v "Permission denied"
find / -name foo 2>&1 | grep -v "Permission denied"

Find Files That Have Been Modified Recently in Linux

Find Files That Have Been Modified Recently in Linux

fd: The Find Command Alternative

Fd: The Find Command Alternative For Mastering File Search In Linux

grep: Find a file by searching contents

grep -r -i "Entering" ~/Downloads/R-3.0.0/

where -r means recursively searching the directory and -i means case insensitive.

Sometimes using -R is more effective because of the symbolic links issue.

$ grep -r -i phpmyadmin /etc/apache2/  # nothing returned
$ grep -R -i phpmyadmin /etc/apache2/

We can also display the row numbers for matches by using the -n parameter in grep.

# What variants appear in dbsnp
grep -n 'rs[0-9]' XXX.vcf

To exclude lines with a pattern, using the -v parameter.

# How many variant were called
grep -v "^#" XXX.vcf | head

To exclude binary files, use -I parameter.

To show only matched filenames, using the -l parameter.

grep -l "iterator" *.cpp
# if we add '-n', the '-n' option won't work.

To search with certain file extensions, use --include argument; see this post.

grep -r -i --include \*.h --include \*.cpp KEYWORD ~/path[12345]  
# escape with \ just in case you have a directory with asterisks in the filenames

How To Find All Files Containing Specific Text On Linux From The Command Line

grep -Rni --exclude-dir={Private,Personal} --include={*.txt,*.js} 'text' ~/Documents
# Exclude hidden directories
grep -R --exclude-dir=".*" 'text' ~/Documents

The only issue with using the -f argument is that grep is going to attempt to interpret the keywords as if they are patterns, which can slow it down when parsing against an extremely large file. So you can also specify the -F parameter, which tells grep to only do exact matches against the strings.

grep -f searchstringsFile filetosearch > output.txt

# -F, --fixed-strings
grep -F searchstring filetosearch > output.txt

If the pattern is saved in a file, use the -f parameter

grep -f PATTERNFILE INPUTFILE

If there are two keywords, use the following

$ grep "begin\|completed" --color swarm_58606147_0.o  # needs an escape
begin 2018-01-12 14:46:05
alignment is completed 2018-01-12 16:45:24
marking duplication is completed 2018-01-12 17:52:01
assign read group is completed 2018-01-12 18:22:49
indel re-alignment is completed 2018-01-12 19:29:32
BQSR is completed 2018-01-12 22:26:22
GATK is completed 2018-01-12 23:43:3
$ egrep "begin|completed" --color swarm_58606147_0.o 
# no need an escape if we use extended regular expressions

We can use R to compute the time spent in each step; see Dealing with dates.

Check https://www.howtoforge.com/tutorial/linux-grep-command/ for more examples

  • Using grep to search only for words / exact match ("-w" option)
  • Using grep to search two different words (egrep -w 'word1|word2' /path/to/file)
  • Count line for matched words ("-c" option)
  • Grep invert match ("-v" option)
  • How to list only the names of matching files ("-l" option)

Preserve colouring after piping grep to grep

https://stackoverflow.com/a/2327216

Use grep --color=always .For example, grep --color=always KEYWORD Myfile | more.

Include/follow soft/symbolic link files

grep grep -Rl instead of "grep -rl". Recall "-l" is to list filename only. See "man grep".

Compressed files

zgrep or zipgrep command

GUI

A GUI version of a tool to search files is searchmonkey (open source, Linux, Windows). On Ubuntu, we install it by

sudo apt-get install searchmonkey

It is also useful to change the settings so we can click a filename and open it in the desired text editor. To do that, go to Settings -> Preferences -> System Call -> Text Editor. I enter 'geany' since I want to use geany to open my C programs. Note. the v2.0 source code needs to be built using i386 gcc library and Qt 4.8.x. Still, I cannot get rid of some errors coming from the source code.

-- option

How To Use grep To Search The --help Output To Find Out What CLI Arguments That Begin With A Dash Do

rm --help | grep -w -- -r

rm --help | grep -w -- '-[rf]'  # multiple one letter

Summary of find and grep commands

Command Examples
find find [DIRECTORY] -iname '*.txt'

find [DIRECTORY] -maxdepth 2 -iname *.php

find -name '*.php' -o -name '*.txt' # OR operator

grep grep -r -i "check_samtools" DIRECTORY/

dpkg -l libgtk* | grep '^i'

Format the output: column

This command will make the output of some command easy to read; see 18 Commands That Will Change The Way You Use Linux Forever.

For example: mount | column -t

Count number of columns: awk

The following command shows the number of columns for the first few rows of a text file.

head MYFILE | awk '{ print NF}'

head MYFILE | awk -F '\t'  '{ print NF}'

Count number of rows in a file: wc

wc -l MYFILE

The source code of wc (or any Linux command) can be found by using this method

brb@brb-T3500:~/Downloads$ which wc
/usr/bin/wc
brb@brb-T3500:~/Downloads$ dpkg -S /usr/bin/wc
coreutils: /usr/bin/wc
brb@brb-T3500:~/Downloads$ sudo apt-get source coreutils

As we can see from the coreutils-8.21/src directory, there are over 100 C programs including <cat.c>, <chmod.c>, <cp.c>, ...<wc.c>.

Print certain rows/lines of a text file

The following example will print out lines 10 to 60 of FILENAME.

sed -n '10,60p' FILENAME

Or to print out line 60,

sed -n '60p' FILENAME

It seems this method is not as fast as I expected. For example, the tail command will immediately print out the result without waiting!

Print a text file with line number: less

How to Use the less Command on Linux

less -N myfile

output colored console to html

Use ansi2html.sh. It only requires gawk.

  1. Use wget to download it
  2. sudo apt-get install gawk
  3. chmod +x ansi2html.sh
  4. colordiff file1 file2 | ./ansi2html.sh > diff.html

using a the result of a diff in a if statement

ls -lR $dir > a
ls -lR $dir > b

DIFF=$(diff a b) 
if [ "$DIFF" != "" ] 
then
    echo "The directory was modified"
fi

Another example

if [ "$(diff file1.html file2.html)" == "" ]; then echo Same; else echo Different; fi

Prompt

Colored prompt

For example, the following code will change the prompt to a light blue color. NOTE that we need ∖[ and ∖] in order to avoid a problem of miscalculating the cursor's starting position.

# blue   
export PS1='\[\e[1;34m\]\u@\h:\w\$ \[\e[0m\]'     # bright blue (good)
export PS1='\[\e[0;34m\]\u@\h:\w\$ \[\e[0m\]'     # darker blue

# yellow
export PS1='\[\e[1;33m\]\u@\h:\w\$ \[\e[0m\]'     # bright yellow
export PS1='\[\e[0;33m\]\u@\h:\w\$ \[\e[0m\]'     # dark yellow (good)

# red
export PS1='\[\e[1;31m\]\u@\h:\w\$ \[\e[0m\]'     # bright red
export PS1='\[\e[0;31m\]\u@\h:\w\$ \[\e[0m\]'     # dark red (good)

# green
export PS1='\[\e[1;32m\]\u@\h:\w\$ \[\e[0m\]'     # bright green
export PS1='\[\e[0;32m\]\u@\h:\w\$ \[\e[0m\]'     # dark green

# cyan
export PS1='\[\e[1;36m\]\u@\h:\w\$ \[\e[0m\]'     # bright cyan
export PS1='\[\e[0;36m\]\u@\h:\w\$ \[\e[0m\]'     # dark cyan (good)

# purple
export PS1='\[\e[1;35m\]\u@\h:\w\$ \[\e[0m\]'     # bright purple (good)
export PS1='\[\e[0;35m\]\u@\h:\w\$ \[\e[0m\]'     # dark purple

Ps1tweak.png

To make a permanent change, we can add the line to ~/.bashrc file and (is it necessary) un-comment the following line

force_color_prompt=yes


Some of my settings in .bashrc file

# Office Linux Mint, bright blue, display current time
# Example: 12:45PM ~/Downloads$
PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] "

# Biowulf and Helix, dark yellow
# Example: biowulf:~/R$
PS1='\[\e[0;33m\]\h:\w\$ \[\e[0m\]'
alias nano="nano -c --softwrap"

# Mac, light green
export PS1="\[\e[0;32m\]mac$\[\e[0m\] "

Shorten prompt

How can I shorten my command line (bash) prompt? It is useful especially in VM.

Add a timestamp to your Bash prompt

PS1 Prompt
default brb@p45t:~/Downloads$
PS1='[\D{%F %T}] \u@\h \W\$ ' [2016-07-08 16:56:48] brb@brb-P45T-A ~/Downloads$
PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] " 10:54AM ~/Downloads$
From here, we can skip %F (not showing the date), \W (not showing the current directory) and change %T to %H:%M (not showing seconds).
export PROMPT_COMMAND="echo -n \[\$(date +%H:%M%p)\]\ "

and the output will be something like:

[07:03AM] user@hostname:~$

zsh: display time to the right hand side

add a line RPROMPT='%*' to ~/.zshrc

Proxy

The 15 Best Web Proxies for Geo-Blocked Content and Online Privacy

Listen to pandora in Europe: install squid proxy

http://www.cyberciti.biz/faq/access-pandora-radio-using-proxy-server-outside-usa/

Interestingly, the firefox connection settings should choose HTTP Proxy instead of 'SOCKS host'.

SSH, scp

See ssh.

Graphical way to display disk usage

For example, to use xdiskusage, we run apt-get install xdiskusage and launch it by xdiskusage ~/.

  • Ubuntu has a built-in program called "Disk Usage Analyzer". Just search it from Dash. Looks useful!

df : Display disk space

df -h
df -h -T  # show the 't'ype of the file system like tmpfs, ext4, squashfs (snap), vfat
df -h -t ext4 # show file systems of given type (ext4 in this example)
df -a     # show all file system (include ones that have a size of zero blocks)

df -h | grep -v snap # ignore snap partitions
df -h | grep -v loop

Note for the NTFS type, it will be reported as fuseblk by mount or df command.

duf

Terminal Tip ‘duf’ is Prettier Alternative to the ‘df’

Disk encryption

LUKS

Encrypt files

croc Is A Tool For Resumable, Encrypted File And Folder Transfers Between Computers (Command Line)

rm command and trash can

Make “rm” Command To Move The Files To “Trash Can” Instead Of Removing Them Completely

du/ncdu and block size: Display directory size with sorting and human readable

Use ncdu program (more interactive). Although it is a command line program, we can use the mouse to move through each directory to see its sub-directories.

ncdu can show the hidden directory size. This is useful. For example, ~/.local/share/Trash and ~/.singularity/docker can take a lot of space.

sudo apt-get install ncdu
ncdu

And the du method.

du -csh *.jpg           # total is at the bottom
du -sh ~/*              # won't include hidden directories, Fast
du -h ~/ --max-depth=1  # include hidden directories, SLOW
du -h ~/ --max-depth=1 --exclude ".*" | sort -nr | cut -f2 | xargs -d '\n' du -sh
du -a -h ~/  # kilobytes will be used, '-a' is to see all files, not just directories.
du -a ~/ | sort -nr | head -n 10   # sort from the largest file size first (in bytes)
                                   # this includes directories and any files under any directories
du -sh * | sort -hr | head -n 10   # this does not go to subdir; only show files and top directories

The --exclude is to hide hidden directories, '-n' is to compare according to string numerical value, and '-r' is to reverse the result.

Note that the 'du' commands may be cheating. See the following screenshot.

DiskUsage.png

The discrepancy is explained by 'sector'. See http://askubuntu.com/questions/122091/difference-between-filesize-and-size-on-disk. Note: it seems 4096 is what I see from all devices.

$ sudo dumpe2fs /dev/sda1 | grep -i "block size"
dumpe2fs 1.41.14 (22-Dec-2010)
Block size:               4096

$ sudo tune2fs -l /dev/sda1 | grep -i "block size"

$ sudo fdisk -l | tail
$ sudo tune2fs -l /dev/mmcblk0p2 | grep -i "block size"

To show a file size in terms of blocks, we can use

ls -s

So for example, if a file takes 150 blocks, and if a block takes 4096 bytes, then the file takes 150*4096/1024 KB on disk.

gdu

gdu Is A Fast Console Disk Usage Analyzer (Alternative To ncdu, du, Etc.)

Find the total size of certain files within a directory

Find the total size of certain files within a directory branch

du -ch ./photos/*.jpg | grep total
find ./photos -type f -name '*.jpg' -exec du -ch {} + | grep total$

Apache benchmark (ab) testing

ab -n 100 -c 10 http://taichimd.us/

Monitor progress of copying/transferring files: pv

How to monitor progress of Linux commands using PV and Progress utilities

# Method 1: rsync
rsync --progress -a sourceDirectory destinationDirectory
rsync --info=progress2 source dest

# Method 2: pv
sudo apt-get install pv
## copy a single file
pv inputfile > outputfile

## multiple files or directories 
tar c sourceDirectory | pv | tar x -C destinationDirectory

## https://stackoverflow.com/a/26226261
docker save <image> | bzip2 | pv | \
     ssh user@host 'bunzip2 | docker load'

rsync

See Backup.

Wireless File Transfer Apps on Linux

The 7 Best Wireless File Transfer Apps on Linux

sudo

How to Control sudo Access on Linux

https://www.howtogeek.com/447906/how-to-control-sudo-access-on-linux/

sudo adduser NEWUSER
sudo usermod -a -G sudo NEWUSER

sudo vs su

The Difference Between sudo and su Explained: password and shell.

How to Keep ‘sudo’ Password Timeout Session Longer in Linux

http://www.tecmint.com/set-sudo-password-timeout-session-longer-linux/

How to run multiple commands in sudo

https://www.cyberciti.biz/faq/how-to-run-multiple-commands-in-sudo-under-linux-or-unix/

Run sudo commands without a password?

Alternative browsers, text browsers

See Browser.

Filezilla

Keyboard shortcut. Especially, Alt+Down=Transfers the currently selected item to an item of the same name in the other pane.

The device is busy

brb@brb-P45T-A:~$ sudo umount /media/brb/TOSHIBA 
[sudo] password for brb: 
umount: /media/brb/TOSHIBA: device is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
umount: /media/brb/TOSHIBA: device is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
COMMAND  PID USER   FD   TYPE DEVICE   SIZE/OFF NODE NAME
VBoxSVC 5600  brb   18w   REG   8,33 4294967295    3 /media/brb/TOSHIBA/Windows 10.ova (deleted)
brb@brb-P45T-A:~$ kill -9 5600
brb@brb-P45T-A:~$ lsof /media/brb/TOSHIBA/
brb@brb-P45T-A:~$ sudo umount /dev/sdc1
brb@brb-P45T-A:~$ 
# fuser -m /dev/sdc1
/dev/sdc1: 538
# ps auxw|grep 538
donncha 538 0.4 2.7 219212 56792 ? SLl Feb11 11:25 rhythmbox

Another handy one is:

umount -l /dev/sdwhatever

mkfs command

dd and mkfs

How to Use the mkfs Command on Linux, How to Format Storage Drives Using the Linux Terminal

dd if=/dev/zero of=~/howtogeek.img bs=1M count=250
mkfs.ext2 ~/howtogeek.img
sudo mkdir /mnt/geek
sudo mount ~/howtogeek.img /mnt/geek
sudo chown dave:users /mnt/geek/

cd /mnt/geek
cp ~/Documents/Code/*.? .

sudo umount /mnt/geek
cd /mnt
sudo rmdir geek

Format a USB drive: exfat

Easily Format A USB Flash Drive On Ubuntu 18.04 Using USB Stick Formatter (mintStick deb & source)

This is a GUI application. After the installation, search "USB Stick Formatter".

For some reason, it doesn't have the 'exFAT' option. My system has installed exFAT drivers. This post said installing exFAT related drivers only helps reading/writing but not formatting.

If I want exFAT format, I need to use the USB Stick Formatter to format the drive first (for example fat32), plug it and then using the following command to format it to exFAT.

sudo apt install exfat-fuse exfat-utils # ubuntu 20.04 and lower
sudo apt install exfat-fuse exfatprogs # ubuntu 22.04 and higher

sudo fdisk /dev/sdc  # g,p,n,p,1,ENTER,ENTER,w
sudo fdisk -l /dev/sdc # the new partition has Id 83 and Type Linux. 

sudo mkfs.exfat -n Staples /dev/sdc1
sudo fdisk -l /dev/sdc # still Linux? but Gparted shows exfat

sudo mount /dev/sdc1 /mnt # to use

Note that fdisk or sfdisk cannot differentiate NTFS/exFAT. But cfdisk or GParted can.

sudo cfdisk /dev/sdX

Create an ext3/ext4 file system on a USB flash drive

umount /dev/sdb1   (depending on the device of course)
lsblk     # check the drive's partition name
sudo mkfs -t ext4 /dev/sdb1
lsblk -f  # Verify

sudo mkfs.ext3 /dev/sdb1
sudo e2label /dev/sdb1 usbdrive   (change the label)

sudo mkfs.vfat /dev/sdb1   # MS-DOS

exFat - cross platform partition format

sudo apt-get install exfat-utils exfat-fuse
# Still need to create a partition (ex. FAT32) first using gparted in order to get it mounted
sudo fdisk -l 
sudo mkfs.exfat -n LABEL /dev/sd**  #  LABEL with whatever you want to label your drive

lsblk -f  # verify the partitions, no sudo is needed

This should delivery a working exfat file system (read and write support, but not formatting the drives with exfat via Gnome Disks and GParted).

Add a new user with home directory; list all users

adduser xxx

adduser is better than useradd since useradd does not create home directory and it does not even ask the password for new user. adduser will interactively ask user information.

To delete the user and home directory, use

deluser --remove-home xxx

To view the user information, type id USERNAME or cat /etc/passwd.

How to List Users in Linux cat /etc/passwd | wc -l

gzip with multi cores: pigz

Use pigz utility. It makes a lot of difference. For example for a 21GB file, gzip can't finish the job after 30 minutes. But pigz only took 7 minutes on a 12-core machine.

According to 'pigz --help', the default threads is the number of online processors, or 8 if unknown.

sudo apt-get install pigz
pigz -9 FILENAME   # best compression method & convert the file to FILENAME.gz

tar cf - paths-to-archive | pigz -9 -p 12 > archive.tar.gz

There is no need to use pigz to un-compress the file. gunzip is fast enough and only takes 4 minutes to decompress.

The '-9' (best compression) option does not make difference (6.6G vs 6.5G).

Note that we have to be careful when we use md5sum to compare compressed files.

Compress a folder without full path name

Suppose we want to compress the folder ~/Documents and its subfolders. We want to include Documents folder name but not /home/brb/Documents name.

# Method 1. Include 'Documents' as the top folder name
cd ~/
tar -czvf tmp.tar.gz Documents
# Method 2. Mind the last dot. Not include 'Documents' as the top folder.
tar -czvf tmp.tar.gz -C /home/brb/Documents .

# Double check the tarball
tar -tzvf tmp.tar.gz  

If we want to strip the upper directories when we uncompress a tar file, use --strip-components. For example, we can use --strip-components=1 to remove the Documents folder.

Fix mess created by accidentally untarred files in the current dir

Suppose I accidentally untar a tarball in /var/www/html/ directory instead of /home/projects/www/current. It created mess in /var/www/html/. The easiest way to fix this mess:

cd /var/www/html/
/bin/rm -f "$(tar ztf /path/to/file.tar.gz)"
## or better ##
tar ztf /path/to/file.tar.gz | xargs -d'\n' rm -v

lzma

squashfs

squashfs

List contents of tar.gz or tar.bz2

tar -tzvf myfile.tar.gz

tar -tjvf myfile.tar.bz2  # replace z with j

gzip: stdin: not in gzip format

I got the following message when I try to run tar -xzvf or tar -tzvf command.

$ tar -tzvf filename.tar.gz 
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
$ file filename.tar.gz 
filename.tar.gz: POSIX tar archive

The answer is How to solve: stdin: not in gzip format.

Solution: Since it was not a gzipped file, a simple tar is able to extract the file: tar xvf MyFile.tar.gz

Extract files, AVFS

See Extract files.

Show folder size for one level only

du --max-depth=1 -h

The graphical tool is called Disk Usage Analyze which is already available on Ubuntu.

Soft link and hard link

Soft link

ln -s /full/path/of/original/file /full/path/of/soft/link/file

Understanding Linux Links Part 1 & Part 2

The order of original and linked above in ln -s is similar to the mount command where we put the original volume first and the system's directory second. See an example here.

But when we issue "ls -l" we see it list the the original file at the end; e.g. /full/path/of/soft/link/file -> /full/path/of/original/file.

Hard link

What's the difference between a hard links and copied files?

  • Why are hard links not allowed for directories?
  • Hard linked file looks the same as the source file when viewed by "ls"
  • Change in either of hard linked file and the source file will affect the other
  • Hard linked file and source file can be deleted separately without affecting the other
echo "abcd" > foo
ln foo foo2
ls -l foo*
echo "efgh" >> foo2
cat foo
rm foo
cat foo2

Self-hosted servers

  • https://github.com/Kickball/awesome-selfhosted This is a list of Free Software network services and web applications which can be hosted locally. Selfhosting is the process of locally hosting and managing applications instead of renting from SaaS providers.
  • Sovereign: A set of Ansible playbooks to build and maintain your own private cloud: email, calendar, contacts, file sync, IRC bouncer, VPN, and more.

Cockpit: manage and monitor my servers using just a web browser

DNS

DNS

Port number is 53. An example is Pi-hole.

Email server

See Mail_server.

Backup

See Backup.

at command: Schedule a task

$ echo "rsync -av /home/tux/ me@myserver:/home/tux/" | at 1:30 AM

$ echo "command_to_be_run" | at 09:00

$ atq  # list of jobs

$ atrm 6   # delete the 6th job

Cron job by root

Note that there is a "user" field for cron jobs defined in /etc/crontab or /etc/cron.d.

  • Place one: /etc/crontab and /etc/cron.daily, /etc/cron.hourly, /etc/cron.monthly, /etc/cron.weekly.
    cat /etc/crontab
    # How to List Daily Cron Jobs
    ls -la /etc/cron.daily
    
  • Place two: /etc/cron.d. It contains "anacron" and "e2scrub_all" on my Debian 11. See How to run a cron job as a specific user?

Running a cron job as a user

Some examples

MIN HOUR DOM MON DOW CMD
30 08 10 06 * $HOME/full-backup >> $HOME/myscript.log 2>&1; echo "Executed at $(date)\n----------" >> $HOME
/myscript.log
#   30 – 30th Minute
#   08 – 08 AM
#   10 – 10th Day
#   06 – 6th Month (June)
#   * – Every day of the week
  • Twice a day
00 11,16 * * * /home/ramesh/bin/incremental-backup 
#    00 – 0th Minute (Top of the hour)
#    11,16 – 11 AM and 4 PM
#    * – Every day
#    * – Every month
#    * – Every day of the week
  • Every 10 minutes
*/10 * * * * /home/ramesh/check-disk-space
# Will only run on odd days:
0 0 1-31/2 * * command

# Will only run on even days:
0 0 2-30/2 * * command

crontab

crontab SOME-CRON-FILE; crontab -l

Make sure the .sh file gives a complete path. For example,

#!/bin/sh
R --vanilla  < arraytoolsip.R

does not work in cron job although it works perfect when we manually run it from the right path. The sh file should be

#!/bin/sh
R --vanilla  < $HOME/Dropbox/scripts/arraytoolsip.R

To disable everything on crontab -l, use one of the following methods:

  • run crontab -e then comment out each line you don't want to run with #. OR
  • run crontab -r to empty the current crontab. OR
  • run crontab with no arguments, and then type Ctrl+D. It will create an empty crontab, overwriting your previous crontab.

GUI

Schedule Commands And Scripts In Linux With Zeit (GUI For Cron And At)

PATH and Shell

Cron knows nothing about your shell; it is started by the system, so it has a minimal environment. If you want anything, you need to have that brought in yourself. For example, to use 'ifconfig' command, I need to give it a complete path in my script file.

$ cat syncIP 
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

and the cron job

06 15 * * * /home/MYUSERNAME/Ubuntu\ One/syncIP > $HOME/Ubuntu\ One/ip.txt 2>&1

See here on how to add environment variable into cron environment.

Disable mail alert

If something went wrong with executing a cron job, cron will output a message "You have new mail in /var/mail/$USER". You can open this file using a text editor. To disable this alert, run 'crontab -e (see this post)

0 1 5 10 * /path/to/script.sh >/dev/null 2>&1
# OR
0 1 5 10 * /path/to/script.sh > /dev/null

Another way is to add MAILTO="" at the top of the crontab file.

Run a command at boot

rc.local

How to enable rc.local shell script on systemd while booting Linux system

Running crontab as root

Use sudo crontab -e to edit. After saving it, no need to initialize it. Use sudo crontab -l to list the cron job.

Display and back up cron jobs

Linux List / Display and view all cron jobs

Check log

sudo grep CRON /var/log/syslog --color

Anacron

Anacron keeps track of the last time a task was run, and if it was missed, it runs it.

Anacron typically runs daily, while cron runs every minute.

cat /etc/anacrontab

GUI cron

md5sum

Linux md5sum Command Explained For Beginners (5 Examples)

How to verify files?

md5sum file1.txt file2.txt file3.txt > hashes
md5sum --check hashes

fsck

Fsck error on boot

fsck error on boot: /dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY

This happened when I resize an Ubuntu partition.

fsck -fy /dev/sda1

Force fsck on the Next Reboot or Boot Sequence

https://www.linuxuprising.com/2019/05/how-to-force-fsck-filesystem.html

https://www.cyberciti.biz/faq/linux-force-fsck-on-the-next-reboot-or-boot-sequence/ Create a blank file /forcefsck and fsck will check your drive next time your reboot.

sudo touch /forcefsck

The fsck was used to fix a journal checksum error on a USB drive which has been formatted as Ext4 was used on a security camera application; see motionEyeOS.

Can I run fsck or e2fsck when Linux file system is mounted?

https://www.cyberciti.biz/faq/can-i-run-fsck-or-e2fsck-when-linux-file-system-is-mounted/

What is the difference between fsck and e2fsck?

https://superuser.com/a/19984

Swap partition

Swap file vs swap partition

Jetson Nano – Run on USB Drive

Mount drive, add a new hard drive

/etc/fstab and blkid

See Fstab.

autofs, /etc/auto.master

Building a network attached storage device with a Raspberry Pi

Fix a malfunctioning USB device or port

5 Ways to Fix a Malfunctioning USB Device or Port on Linux

Check the physical health of a USB stick

Linux check the physical health of a USB stick

USB drive

  • Rename USB drive partition label. It seems if a device does not have a label, Ubuntu will use its 32-digit UUID as the mount point (eg. /media/$USER/$Long_UUID). This is very cumbersome. To fix that, we can open the Disks utility and select the partition of the device. Click the two-gear icon and pick Edit Filesystem... where we can change the filesystem label. After that, we can reject the USB and re-plug it to see the new mount directory based on the new label we specified (/media/$USER/$Label). We can also use the command lsblk (no sudo needed) to check.
  • If I use "GParted" utility to check the "partition name ", it is not the same as the name I just specified through the "Disks" utility. But the "Information" window give a complete data. It is a little confusing that the partition label becomes the filsystem label and the Partition name shown on GParted was different & seems not to be used.

GpartedinfoSanDisk.png

Run the following to confirm the USB device is detected.

sudo fdisk -l
# OR
dmesg | grep -i "SCSI"

Now suppose the usb device is found in dev/sdb1.

sudo mkdir /mnt/usb
sudo mount -t vfat -o rw,users /dev/sdb1 /mnt/usb

The above mount command assumes the usb drive has Windows vfat partition and users give non-root users the ability to unmount the drive. If the USB drive is partitioned linux ext2/3, we can merely run mount command as

sudo mount /dev/sdb1 /mnt/usb

At the end, run umount command like

sudo umount /mnt/usb

To make the mounting automatically, edit the file /etc/fstab.

/dev/sdb1       /mnt/usb           vfat    defaults        0       0 
/dev/sdb2       /mnt/usb2          ext3    defaults        0       0
UUID=XXXXXXXXXX /mnt/usb3       ntfs-3g    rw              0       0

and run

sudo mount -a

Mount an iso file

sudo mkdir -p /mnt/mount_point # create a mount point
sudo mount -o loop /home/user/disk.iso /mnt/mount_point
mount  # verify

Mount remote Windows share

Sharing files with Windows by using NitroShare

Simple way of Sharing files between Ubuntu 16.04 and Windows 10 by using open-source NitroShare which is based on Qt framework.

NTFS usb drive in xubuntu

http://xflinux.blogspot.com/2011/01/mount-ntfs-volumes-automatically-in.html

sudo apt-get install ntfs-config

Now go to Applications>> System>> Ntfs Configuration Tool

Expand the "Advanced Configuration" and select all those partitions you want to be auto mounted and writable( The tool will detect all partitions at its startup).

Make sure the " Enable write support for internal devices" option is selected. Now click Close.

Many drives, one folder

Partition tables

Partition Tables and the Dangers of Editing Them

parted command

How to partition a disk in Linux

Recommended partition schemes

HOME /home directory

How to Move Your Linux home Directory to Another Drive

/var directory filled up

How to move /var directory to another partition

blkid | grep sdc1  # get UUID 
mkdir /mnt/newvar
mount /dev/sdc1 /mnt/newvar
df -h /mnt/newvar
rsync -aqxP /var/* /mnt/newvar  # q=quiet,x=one-file-system, P=partial,progress
umount /mnt/newvar/  /mnt/var/
nano /etc/fstab
# UUID=XXXX   /var    ext4  defaults  0   2

Reboot

Why put things other than /home to a separate partition?

Why put things other than /home to a separate partition?

The /var partition is used by Docker and Apache.

/home, /boot and /var partitions can be separated.

Process/job

ps and top commands

How to Use the ps Command to Monitor Linux Processes, Linux how long a process has been running?

ps -C shutter # Listing only a Process by Command
              # Adding the 'watch' command to show the process in real-time
ps -C dd --format pid,cmd,%cpu # Show PID, CMD and %CPU

sudo ps -p {PID} -o pid,cmd,lstart,etimes,etime

ps -e | less # Listing Process for All Users

ps -eH --forest | less # hierarchy

ps -e | grep firefox # Listing Processes by Name

ps -p 3403 # Listing Processes by Process ID

ps -u mary  # Listing Processes Owned by a User

sudo pkill top # Killing Processes by Name

sudo killall top # Killing Multiple Processes by Name

Kill a process and the pstree command

  • Killing a process and all of its descendants. This covers a PPID, PID and more importantly PGID, SID. Also ps j -A command can show these IDs for the running processes.
    $ tail -f /var/log/syslog | grep "CRON" &
    $ ps j
    $ kill -SIGTERM -- -($Some_PGID)
    
  • pgrep & kill
    # find the PID
    pgrep ProgramName
    # Kill the ProgramName process
    kill -9 PID
    
  • killall. For example, if Firefox is acting up (as Firefox will do from time to time) simply type killall firefox and it should kill the application completely. In the rare circumstances that this doesn’t work you can always type xkill and then click on the window that won’t close; this will completely close a given window immediately. See this. To kill a privileges process, use for example sudo killall crond.
    sudo killall -u USERNAME
    

Kill a process running on a specific port

Kill a Process Running on a Specific Port in Linux (via 4 Methods)

How to Kill Zombie Processes on Linux

How to Kill Zombie Processes on Linux

Simulate/produce high cpu load

How can I produce high CPU load on a Linux server?

# method 1:
sudo apt install stress
stress --cpu 3

# method 2:
for i in 1 2 3 ; do while : ; do : ; done & done
jobs   # list background jobs
for i in 1 2 3 4; do kill %$i; done  # kill "job" (not "PID") 1,2,3,4

ps, pgrep and pidof: How much resource is used by a process

Find the process ID first by ps -ef | grep APPLICATIONAME where "-e" is to show the running processes and "-f" is for a full listing. Then

ps -p <pid> -o %cpu,%mem,cmd

For example,

$ ps -ef | grep akregator
brb      15013  1942  1 10:41 ?        00:00:05 akregator --icon akregator -caption Akregator
brb      15186 24045  0 10:50 pts/11   00:00:00 grep --color=auto akregator
$ ps -p 15013 -o %cpu,%mem,cmd
%CPU %MEM CMD
 1.0  0.8 akregator --icon akregator -caption Akregator

pgrep

08:49AM ~$ ps -ef | grep firefox
brb       7798  7778  0 08:49 pts/2    00:00:00 grep --color=auto firefox
brb      25486 24869  0 Sep10 ?        00:42:48 /usr/lib/firefox/firefox
brb      25612 25486  0 Sep10 ?        00:19:49 /usr/lib/firefox/firefox .....
08:49AM ~$ pgrep firefox
25486

pidof

08:49AM ~$ pidof firefox
27951 25961 25612 25486
08:51AM ~$ pidof /usr/lib/firefox/firefox
27951 25961 25612 25486

$ kill $(pidof firefox)

Avoid concurrency

Avoid These Problems By Limiting Bash Scripts to Run Once At A Time. pgrep, lsof and flock commands.

All You Need To Know About Processes in Linux

http://www.tecmint.com/linux-process-management/

wait command and background jobs

The wait command in Linux is a shell built-in command that pauses the execution of a shell script until all background jobs or specified JobID/PIDs terminate and return their exit status.

# Example 1: Wait for all background processes to finish
command1 &
command2 &
wait
echo "All background processes have finished."

# Example 2: Wait for a specific process to finish
command1 &
PID=$!
command2 &
wait $PID
echo "Command1 has finished."

run commands in a background and allow log off

nohup /path/to/script >output 2>&1 &

Or to disable output and be more safe. It also explains the concept of file descriptor/fd in Unix.

nohup command </dev/null >/dev/null 2>&1 & 

See also Anonymous named pipe.

See also How to Setup OpenVPN on Fedora 24+ where we use nohup openvpn ... & to start the connection in the background and also make it not terminate on exiting the terminal.

job: How do I send an already-running process into the background

Steps:

  1. 'Ctrl+Z' to stop (pause) the program and get back to the shell. It sends SIGTSTP to a foreground application.
  2. bg to run it in the background.
  3. jobs -l to get the jobID and process ID
  4. disown -h [job-spec] where [job-spec] is the job number (like %1 for the first running job; find about your number with the jobs command) so that the job isn't killed when the terminal closes.

Stopped job

A stopped job is one that has been temporarily put into the background and is no longer running, but is still using resources (i.e. system memory). Because that job is not attached to the current terminal, it cannot produce output and is not receiving input from the user.

  • jobs -s showing stopped jobs
  • jobs -l showing the job PID

Send kill to a stopped job, it will do nothing but queue than bring it in in foreground, it will terminate. So don't repeatly sending a 'kill' command.

  • fg %1 move the stopped job ID #1 to the foreground (works)
  • kill %1 # kill job ID #1
  • kill 12345 # kill job PID 12345
  • kill -9 `jobs -ps` may not work
  • kill -9 $(jobs -p)

nice

How to Set Process Priorities With nice and renice on Linux

watch command

Watching activity on Linux with watch and tail commands. Both the watch -n and tail -f commands can provide auto-updating views of information/

We can use the watch command to monitor a specific process such as the progress of the dd command.

Terminal 1

watch -n 10 who
watch ps -C dd --format pid,cmd,%cpu

Terminal 2

dd if=/dev/zero of=/dev/null

Use --color for color output.

while + sleep

How To Repeat A Command Every X Seconds On Linux: watch, while + sleep,

ulimit

Notepadqq - Notepad++-like editor

Notepadqq. It is written using Qt. It does not have printing function:(

Note apps that can sync

Top 8 Notepad Apps for Linux That You Can Sync. Some are compatible with Evernote.

Evernote

Evernote alternative

How to Install Turtl Server - Evernote Alternative - on Ubuntu 16.04

Backup/restore Evernote

https://www.makeuseof.com/tag/backup-restore-evernote/

Markdown

Preview markdown/view markdown offline

sudo pip install grip
grip readme.md
# title 1
![screenshot](myfile.png?raw=true)
  • Chrome markdown preview plus extension does not show images from github.

Markdown editor

Text editor with navigation

Text editor with navigation

nano/pico editor

The nano editor is also called pico in R. See ?edit in R.

nano editor

vi editor

vi editor

Cloud

Cloud

Boot

U-boot

http://www.denx.de/wiki/U-Boot

Pandora linux client

COW (copy on write) file system

filesystem

tmpfs and /dev/shm

Apache redirection

http://cran.r-project.org/mirror-howto.html

Redirect a Website URL from One Server to Different Server in Apache

Important linux directories

Filesystem Hierarchy Standard, Wikipedia

  • /bin - executables used by the base system
  • /boot
  • /dev
  • /etc - configuration files
  • /media
  • /mnt
  • /opt - optional application packages
  • /proc - process information only. Access Kubernetes Objects Data From /Proc Directory
  • /sbin - critical executables for running the system, but should be used by superuser
  • /usr - user programs and data. For example /usr/bin contains most of the libraries used by apps. /usr/share/ contains Architecture-independent data (eg some pretty images are located in /usr/share/backgrounds)
  • /var - variable data such as databases, mails spools and system logs.

Difference of /bin, /sbin, /usr/local/bin, ...

  • /bin : For essential binaries; e.g. bash, cat, ls.
  • /sbin : is similar to /bin but for scripts with superuser (root) privileges required; e.g. shutdown command is located here. Local users have to use sudo to run binaries here.
  • /usr/bin : Same as first, but for general system-wide & non-essential binaries; e.g. grep, zip, docker, etc.
  • /usr/sbin : Same as above, but for scripts with superuser (root) privileges required.
  • /usr/local/bin or /usr/local/sbin for system-wide available (personal) scripts. For example, install docker-compose is merely to download the binary and place it under /usr/local/bin/ directory.

If you want to create your own scripts and make them available to all users, you’re pretty safe adding them to /usr/local/bin. Or to add my scripts to my local bin (~/bin) and then I create a symbolic link in /usr/local/bin to the commands I want to make public. As a result, I can manage all my scripts from the same directory but still make some of them publicly available since /usr/local/bin is added to $PATH. See this post.

DHCP

DHCP server IP

Linux find DHCP server IP address using CLI

Get a New IP Address

dhclient -r   #  release your IP Address

dhclient   #  get your DHCP to issue you a new IP Address based on how it’s been configured.

Open a file/URL using the default application from the command line

See also

Check a file's encoding

file -bi myfile

For example,

file -bi Downloads/hmv_.rc 
# text/x-c++; charset=utf-16le

Know you system using the command line

Alerting and visualization tools

5 alerting and visualization tools for sysadmins

System monitor tools (TUI)

glances command: more than htop

Glances is similar to htop but it provides network stats and disk usage too. It also supports web UI. Install it by sudo apt-get install glances.

conky and autostart

For auto start on Lubuntu, see How can I add new autostart programs in Lubuntu?

On Lubuntu 18.04, add the path to the application to ~/.config/lxsession/Lubuntu/autostart

top and htop command

nmon

CPU frequency

How To Optimize Performance And Battery Life With Auto-cpufreq In Linux

What is the correct way to view your CPU speed on Linux? (x86)

watch -n.1 "cat /proc/cpuinfo | grep \"^[c]pu MHz\""

How can I get the current CPU frequency of an ARM processor on Ubuntu?

ls /sys/devices/system/cpu/cpu0/cpufreq/

scout_realtimep

This is used by Dataplicity

gtop command (100% Javascript)

https://www.cyberciti.biz/howto/gtop-awesome-system-monitoring-dashboard-for-terminal/.

Pros:

  • CPU history graph in time
  • Memory history graph in time (not useful)
  • Network bandwidth usage is real-time. It is accurate as what nload gives.
  • Percentage usage of memory, swap, disk usage
  • Top processes
$ docker run --rm -it \
    --name gtop \
    --net="host" \
    --pid="host" \
    aksakalli/gtop

$ sudo apt install npm nodejs
$ npm install gtop -g
$ gtop
  • Press p to sort by process ID (PID).
  • Press c to sort by CPU usage.
  • Press m to sort by memory usage.

It can be installed on Linux Mint 18.2 but not in Ubuntu 14.04 or raspbian (9 stretch).

$ npm install gtop -g
npm http GET https://registry.npmjs.org/gtop
npm http GET https://registry.npmjs.org/gtop

npm http GET https://registry.npmjs.org/gtop
npm ERR! Error: CERT_UNTRUSTED
npm ERR!     at SecurePair.<anonymous> (tls.js:1370:32)
npm ERR!     at SecurePair.EventEmitter.emit (events.js:92:17)
npm ERR!     at SecurePair.maybeInitFinished (tls.js:982:10)
npm ERR!     at CleartextStream.read [as _read] (tls.js:469:13)
npm ERR!     at CleartextStream.Readable.read (_stream_readable.js:320:10)
npm ERR!     at EncryptedStream.write [as _write] (tls.js:366:25)
npm ERR!     at doWrite (_stream_writable.js:223:10)
npm ERR!     at writeOrBuffer (_stream_writable.js:213:5)
npm ERR!     at EncryptedStream.Writable.write (_stream_writable.js:180:11)
npm ERR!     at write (_stream_readable.js:583:24)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Linux 4.4.0-119-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "gtop" "-g"
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.10

gotop

A terminal based graphical activity monitor inspired by gtop and vtop. It is quite beautiful.

Gotop – Yet Another TUI Graphical Activity Monitor, Written In Go

Compared to gtop, it has a temperature monitor. However, it can only show the average CPU usage (one line) on my Xeon computer.

git clone --depth 1 https://github.com/cjbassi/gotop /tmp/gotop
/tmp/gotop/scripts/download.sh
sudo cp gotop /usr/local/bin; rm gotop
gotop

Note the temperatures do not show up in Raspbian (raspberry pi 3 b+).

termui: Golang terminal dashboard

https://github.com/gizak/termui

Bashtop and btop

S-tui command

Monitor Linux CPU temperature, frequency, power in a graphical way

below

below: a time traveling resource monitor

System monitor tools (GUI)

Comparisons:

Some lists:

Linux-Dash

https://github.com/afaqurk/linux-dash. Not working when I tested on RPi and Ubuntu.

Nagios

Zabbix

Munin and Monit

Server Monitoring with Munin and Monit on Ubuntu 16.04 LTS

Cacti

sysstat, sar

# CPU
sar 2 10 # every two seconds, 10 times
# Memory
sar -r  # look at the kbcommit and commit columns

sar -r -f /var/log/sysstat/sa02

Stacer

Linux System Optimizer and Monitoring

Prometheus

Curses and ncurses: TUI library

Position text on your screen in Linux with ncurses

Calcurse

Keep up with your calendar and to-do list with Calcurse

Bitbucket (free for 5 users)

Bitbucket 101

  • Unlimited private repos
  • Code reviews
  • JIRA integration
  • REST API
  • Custom domains

See this post to know how to fix the problem of unknown author. In short, when I uncheck "Use global user setting" from Repository-> Repository Settings -> Advanced does the commit author change as expected.

See here for a list of Android apps related to bitbucket.

Image

See Images.

GIMP

Reload/Refresh .profile file

https://askubuntu.com/a/59127

. ~/.profile

. is a bash builtin and a synonym for source, see man bash.

After changing the .profile file, you have to logout from your account and login, then it will be sourced once automatically.

History of commands

history command with date and time

Running the following code once and history will give date and time the next time you issue the history command.

echo 'export HISTTIMEFORMAT="%Y-%m-%d %T "' >> ~/.bashrc

Note that the original post asks to write the line to ~/.bash_profile but this is not working in the desktop environment.

Note that on zsh, the above method is not supported. We can use history -i instead. Type man zshoptions or man zshbuiltins for more information.

Bang bang - Run a command/Fetch parameters from previous history

  1. ^P: Move up through the command history list one command at a time.
  2. ^N: Move down through the command history list one command at a time.
  3. !!: Run the previous command. For example, we can run sudo !! in order to run the previous command with sudo.
  4. !n: Run command number n (useful)
  5. !string: Run most recent command starting with characters in string (useful). For example, !ls
  6. !?string: Run most recent command containing characters that match string
  7. !*: Fetch parameters from last command (useful). For example, if we run "ls /var" first. Then when we run stat !*, it would run stat /var. Or we can run cd !* and it will cd to /var directory.
  8. !_: Fetch the last parameter from last command. For example, if we run "ls /var/ /etc" first. Then when we run stat $_, it would run stat /etc. (zsh shell only)
  9. Ctrl + r and type a keyword (most useful). Press ctrl + r to scroll the match. This is called reverse i search.

For example,

!-1
!4
!tail

Recall commands with reverse-i-search

Ctrl + r. See Bash bang commands: A must-know trick for the Linux command line

To continue with the search, just hit Ctrl + r keys again.

To run a forward search, hit Ctrl + s. How to cycle through reverse-i-search in BASH?

Increase history limit

http://unix.stackexchange.com/questions/17574/is-there-a-maximum-size-to-the-bash-history-file Unlimited Bash History

$ echo $HISTSIZE  # $HISTSIZE variable controls how much history is displayed 
500
$ export HISTSIZE=1000
$ echo “HISTSIZE=1000” >> ~/.bashrc

# $HISTFILESIZE variable controls how many commands are retained in your .bash_history file.
$ echo $HISTFILESIZE
2000
$ wc -l .bash_history
2000 .bash_history

Not to add to bash history

Add a space after the command.

It is useful if there is a password in the command.

For example,

$ ls ~/             # this won't be recorded in history
$  ls ~/Downloads/  # this will be recorded in history
$ history

Delete a single command from history

To stop adding history entries, you can place a space before the command, as long as you have ignorespace in your HISTCONTROL environment variable.

You can force Bash to exclude commands starting with empty space by placing this in your .bashrc file:

export HISTCONTROL=$HISTCONTROL:ignorespace

How to Clear Bash History on Linux

$ cat /dev/null > ~/.bash_history && history -c && exit

multiple terminals

Use ‘’’history -a’’’ to write the history to the file if we do not plan to close the terminal. See How to use the history command on Linux.

Listen to HiChannel internet radio

Use Radio Tray

I use it to listen m3u file (VLC also supports it too).

Web Analytics Reporting Tools

Painting software

  • Pinta. It can be install by apt-get command. It works just line Window's paint. Ctr + v to paste an image and save to a file. To crop an image, click the selection tool on the most left hand side (it's a black color on v1.6 but a gray color on v1.7), then select a rectangle. Now click 'Image' > 'Crop to Selection' to finish. Pinta New Release After 5 Years. Here’s How to Get it!
    sudo add-apt-repository ppa:pinta-maintainers/pinta-stable
    sudo apt update
    sudo apt install pinta
    
  • mtPaint. It is included in Odroid - xu4 - Lubuntu 14.04. To crop an image, just select an area and click Image > Crop. It can be used to take a screenshot from the desktop by using either the application or through the command line (mtpaint -s). It will then display the screenshot in the application if you use the command line.
  • MyPaint

Take a screenshot (and edit them)

See Take screenshots.

Cozy - audiobook player

ebook readers

7 Best eBook Readers for Linux: Calibre, FBReader, Okular, Lucidor, Bookworm, Easy Ebook Viewer and Buka.

Calibre - Read ebook in epub format

See Calibre

RSS reader

Some references:

  1. 5 Best Feed Reader Apps for Linux
  2. 14 Best RSS Feed Readers for Linux in 2018. It contains nice screenshots.

Some examples:

  • Fluent Reader. Open source. Linux, Windows, macOS.
  • Akregator. KDE based. This is preinstalled in CentOS-KDE under the Internet category. It is also called 'Feed Reader'.
  • QuiteRSS. It works on Linux, Windows and MacOS.
  • Liferea. GTK based. It is considered one of the best RSS feed readers on Ubuntu Linux. It can synchronize with several online feed managers such as InoReader among others.
  • FeedReader. Looks nice. Works with several online feed managers.
  • Newsbeuter: RSS feed in terminal
  • Newsboat: terminal. Newsboat: The Best Terminal-Based RSS Feed Reader for Linux. Not for general use since it assumes the articles are all text-based.
  • RSSOwl. Depends on Java. Cross platform.
  • Firefox and Thunderbird have built-in support for RSS.

Clear gibberish all over the screen

Just type “reset”. See BASH Fix Display and Console Garbage and Gibberish on a Linux / Unix / macOS. It is useful, for example, accidentally I run cat command over binary file.

Display/screen

Turn off/on your monitor via command line

xset dpms force off # Press any key to turn it on 
xset dpms force on
xset -q # check the status of the X server settings

If we want to turn off/on the screen via ssh, add

export DISPLAY=:0.0

first before calling the xset command, or use '-display' argument

xset -display :0.0 dpms force off 
xset -display :0.0 dpms force on 

autoxrandr

Plug your laptop into different monitor setups. https://www.donarmstrong.com/posts/autorandr/

Move a window without clicking the titlebar

Hold down the Alt key and then click in the window anywhere, and move your mouse.

Add new screen/display resolutions

xrandr | grep maximum
gtf 800 480 59.9  # give some output used in the following line
xrandr --newmode "800x480_59.90" 29.53 800 816 896 992 480 481 484 497 -HSync +Vsync
xrandr --addmode "DISP3 BG" 800x480_59.90
xrandr --output "DISP3 BG" --mode 800x480_59.90

I cannot find the file /etc/X11/xorg.conf in my UDOObuntu 2 beta 2. It seems this file does not exist anymore. See this post about how to re-create it.

Wayland

  • echo $XDG_SESSION_TYPE to check whether X11 or Wayland is in use
  • To change from wayland to X11:
    • Method 1: log out, click the username, choose Xorg and type the password
    • Method 2:
sudo nano /etc/gdm3/custom.conf
Change the line WaylandEnable=true to WaylandEnable=false And restart the system1.
loginctl show-session $(awk '/tty/ {print $1}' <(loginctl)) -p Type | awk -F= '{print $2}'

export DISPLAY

  • What is the $DISPLAY environment variable? The value of the display environment variable is:
    hostname:displaynumber.screennumber
    
  • If we want to run a GUI app on a remote computer (such as Raspberry Pi/Beaglebone Black) and show the GUI app on the remote computer's screen using ssh, we can issue the following command before running the app.
    export DISPLAY=:0.0
    

See which groups you belong to, id & group commands

id <username>
groups 
groups <username>

Main Types of User Accounts on Linux

The 4 Main Types of User Accounts on Linux:

  • Superuser Account
  • Regular Accounts
  • System Accounts (Core OS functionality, eg root, bin, sys, daemon) awk -F: '$3 <= 100 {print $1, $3, $7}' /etc/passwd Note that the third field is the user ID (UID). System accounts generally have UIDs below 100 (though this threshold may vary slightly depending on your distribution).
  • Service Accounts (eg SQL, apache).

List all user groups

How to List All User Groups on Linux To see a list of groups

cat /etc/group
# OR
getent group

Note that "getenv group" Lists groups from all configured sources, including both local and networked sources, depending on your system’s NSS (Name Service Switch) configuration (in /etc/nsswitch.conf).

finger: show user information

finger USERNAME

groupadd, chgrp, usermod, ACL (access control lists)

sudo mkdir -p /var/www/reports/
sudo groupadd project 

sudo usermod -a -G project tecmint 
sudo chgrp -R project /var/www/reports/
sudo chmod -R 2775 /var/www/reports/

create more system users and add them to the directory group as follows:

sudo useradd -m -c "Aaron" -s/bin/bash -G project aaron
sudo useradd -m -c "John" -s/bin/bash -G project john
sudo useradd -m -c "Ravi" -s/bin/bash -G project ravi

sudo mkdir -p /var/www/reports/aaron_reports
sudo mkdir -p /var/www/reports/john_reports
sudo mkdir -p /var/www/reports/ravi_reports

See who's in a group

grep '^group_name_here:' /etc/group

finger USERNAME # See more detail about a user

Add a standard user to sudo group

This is useful on Debian distribution where a new user does not have the sudo power. First log in as root,

# usermod -aG sudo username

Shared library management

http://www.cyberciti.biz/tips/linux-shared-library-management.html

  1. ldconfig : Updates the necessary links for the run time link bindings.
  2. ldd : Tells what libraries a given program needs to run.
  3. ltrace : A library call tracer.
  4. ld.so/ld-linux.so: Dynamic linker/loader.

Log files

$ ls -lt /var/log

ssh log files: /var/log/auth.log

  • /var/log/syslog: it is useful to use tail -f /var/log/syslog to show the log in real time
  • /var/log/auth.log: it includes ssh log in information and lots of CRON sessions opened and closed every minutes.

And

lnav (The Logfile Navigator)

How to Monitor Log Files in Real Time in Linux (Desktop and Server) . sudo apt install lnav; sudo lnav

Apache log

  • /var/log/apache2/error.log (small 83K). Useful to troubleshoot errors/crashes of Apache.
grep "May 08" /var/log/apache2/error.log
  • /var/log/apache2/access.log (large 10M)

mail

/var/log/maillog

Logrotate

How to Setup Logrotate on Linux (to Keep Your Server from Running Out of Space)

uprecords command

uptime command

uptime
watch -n 60 uptime

Windows

Find out from the logs what caused system shutdown?

How to find out from the logs what caused system shutdown?

Get notified when a system is rebooted

Get Notified When Your Raspberry Pi is Booted with Pushbullet. This makes use of /etc/rc.local file. If it does not work, we can use cron to run a command at startup; see sending an email on boot.

timeout command

Linux command similar to top to show hard disk activity

Use iotop. On ubuntu, we can use sudo apt-get install to install it. Use sudo iotop to launch it. Use -o to show processes that are actually doing IO.

sudo apt-get install iotop

sudo iotop -o -u $USER

Another program is iostat and the -d (disk) option. The -x option will display extension I/O status.

sudo apt-get install sysstat
iostat -dx 5 # every 5 seconds

24 iostat, vmstat and mpstat Examples for Linux Performance Monitoring

curl and wget

See Curl.

Torrent

Torrench

Torrench: How To Search And Download Torrent Files Using Terminal (Linux, Mac, Windows)

aria2 - command line downloader supports torrents and multi-connection

aria2 command examples

The -x argument helps a little bit. Download a file 112MB; see https://www.archlinux.org/download/

$ time aria2c  http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 16 seconds
$ time aria2c -x10 http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 11 seconds

Axel

It can create an unlimited number of worker threads to download any kind of data. See https://www.beginnersheap.com/top-5-command-line-download-accelerators-linux/

lftp

Apply a patch to source code

For example Tophat 2.0.12 compatibility with Samtools 1.0,

$ ls
support_for_tophat_1.patch  tophat-2.0.12  tophat-2.0.12.tar.gz

$ grep -r -i "check_samtools" tophat-2.0.12/
tophat-2.0.12/src/tophat.py:def check_samtools():
tophat-2.0.12/src/tophat.py:        check_samtools()

$ cp support_for_tophat_1.patch tophat-2.0.12/src/
$ cd tophat-2.0.12/src/
$ patch tophat.py < support_for_tophat_1.patch 
patching file tophat.py
Hunk #1 succeeded at 1540 (offset 3 lines).
Hunk #2 succeeded at 1563 (offset 3 lines).

IP address fundamental

http://www.howtogeek.com/133943/geek-school-learning-windows-7-ip-addressing-fundamentals/.

There are three classes for private IP ranges.

  • 1-126.0.0.0 from Class A
  • 128-191.0.0.0 from Class B
  • 192-223.0.0.0 from Class C

Subnet

Gateway IP address

How To Find Default Gateway IP Address In Linux And Unix From Commandline

Get internal IP address

$ hostname -I

$ ifconfig  # also works on Android through Termux

Private/internal/local IP/network

https://en.wikipedia.org/wiki/IPv4#Private_networks

  • 10.0.0.0 – 10.255.255.255
  • 172.16.0.0 – 172.31.255.255
  • 192.168.0.0 – 192.168.255.255

There are other special-use addresses for private networks

  • 100.64.0.0 to 100.127.255.255 (similar to private IP addresses like 192.168.x.x or 10.x.x.x)

Get external IP address

Using a browser: Google.com and type "my ip"

How to find your IP address in Linux

Command for determining my public IP? wget -qO- https://ipecho.net/plain ; echo

5 Commands to Find the IP Address of a Domain in the Linux Terminal

https://github.com/jakewmeyer/Geo (one shell script)

How to Find the Public IP Address on a Linux System

It seems there is no way to get the external IP address without not using external services.

host myip.opendns.com resolver1.opendns.com
# Look for the bottom line output  myip.opendns.com has address XXX.XX.XX.XXX

# https://unix.stackexchange.com/a/81699
sudo apt-get install dnsutils
dig +short myip.opendns.com @resolver1.opendns.com
# OR
curl ifconfig.me   # by google
                # also works on Android through Termux
# 
curl http://ipecho.net/plain; echo
# OR
curl ipv4.ipogre.com   

To store my IP in a shell variable

myip="$(dig +short myip.opendns.com @resolver1.opendns.com)"
echo "My WAN/Public IP address: ${myip}"

The above only gives the IP. The following method gives geo information too.

curl ipinfo.io # ifconfig.me, icanhazip.com, ipecho.net/plain, ifconfig.co
# OR give a specific IP (domain name does not work)
curl ipinfo.io/216.58.194.46

{
  "ip": "216.58.194.46",
  "hostname": "dfw25s12-in-f14.1e100.net",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.4192,-122.0574",
  "org": "AS15169 Google Inc.",
  "postal": "94043"
}

IP geolocation

Test url: ubuntu.mirrors.pair.com

curl https://ipapi.co/8.8.8.8/json/

curl https://ipinfo.io/8.8.8.8
  • command line - input is a web address
IP_ADDRESS=$(dig +short example.com)
curl https://ipapi.co/$IP_ADDRESS/json/

Domain, WHOIS

  • WHOIS LOOKUP. For example, consider "r-pkg.org" domain,
    • The 'Sponsoring Registrar' shows who is the sponsoring registrar (eg GoDaddy.com).
    • The 'Registrant Name' shows who registered this domain.
    • Command Line Interface.
      sudo apt-get install whois
      whois r-pkg.org 
      

Subnet

IPv4

  • Class A: 255.0.0.0 or /8;
  • Class B, 255.255.0.0 or /16;
  • Class C, 255.255.255.0 or /24.

For example, in the subnet 192.168.5.0/255.255.255.0 (192.168.5.0/24) the identifier 192.168.5.0 commonly is used to refer to the entire subnet.

In the /16 subnet 192.168.0.0/255.255.0.0, which is equivalent to the address range 192.168.0.0–192.168.255.255

IPv6

ping command

ping uses the ICMP Echo Message to force a remote host to echo a packet back to the local host. If packets can travel to and from a remote host, it indicates that the two hosts can successfully communicate.

Check if a server is up/down if pining to that machine is not allowed

Hint: use nmap to scan open ports

nmap -PS22 -p22 <hostname> # port 22 only
# OR
nc -z -v <hostname> 22

Shell script to check whether a server is reachable?. I found if a server is up and I am trying a closed port, it will take about 2 minutes before it returns.

if nc -z $server 22 2>/dev/null; then
    echo "$server ✓"
else
    echo "$server ✗"
fi

6 Methods to Quickly Check if a Website is up or down from the Linux Terminal

Check if Sites are Online using a PHP script

How to Use Crontab to Automate Repetitive Tasks in Linux

Build a home network

IP Subnet Calculator

https://www.dan.me.uk/ipsubnets?ip=10.0.0.0

  • CIDR block IP range (network - broadcast) Subnet Mask IP Quantity
  • 10.0.0.0/24 10.0.0.0 - 10.0.0.255 255.255.255.0 256
  • 10.0.0.0/16 10.0.0.0 - 10.0.255.255 255.255.0.0 65536=256^2
  • 10.0.0.0/8 10.0.0.0 - 10.255.255.255 255.0.0.0 16777216=256^3

How Use Your Router and ISP’s Modem/Router Combo In Tandem

http://www.howtogeek.com/255206/how-use-your-router-and-isps-modemrouter-combo-in-tandem/

Troubleshoot and repair network problems

http://www.linuxuser.co.uk/features/troubleshot-repair-linux-networks

Computer 1 can ping Computer 2 but not reverse

Use the route command to solve. See also this post.

Simple Network Management Protocol (snmp)

Monitor network by Cacti (GUI)

Monitor network by command line

3 Simple, Excellent Linux Network Monitors: iftop, nethogs and vnstat.

bandwidth

bandwhich Shows What`s Taking Up Your Network Bandwidth On Linux And macOS

iftop

Use the interface top iftop command. On ubuntu, we need to use sudo apt-get install iftop and then run it by sudo iftop -i eth0. After that, we can press some keys to toggle options.

  • p: port
  • s: source
  • d: destination

See thegeekstuff.

It is strange that the output shows other devices names in my network.

$ dig A pandora.com
$ ipcalc -b 208.85.40.20
$ sudo iftop -F 208.85.40.20/24 -i wlan0

nethogs

$ sudo nethogs wlan0

Why does the snapd service use so much data?

nload

nload -m

nload – Monitor Linux Network Bandwidth Usage in Real Time

The result is the same as gtop (gtop is cooler) gives.

bmon

https://www.tecmint.com/bmon-network-bandwidth-monitoring-debugging-linux/

vnstat for network traffic monitor

# 1. Install vnStat
sudo apt-get install vnstat

# 2. Pick a Interface to Monitor using vnStat
vnstat -u -i eth0
vnstat --iflist
vnstatd -d # start the daemon
ps -ef | grep vnst

# 3. vnStat Basic Usage
vnstat

# 4. vnStat hours, days, months, weeks Network Data
vnstat -d
vnstat -m

# 5. Export the data to Excel or other DB
vnstat --dumpdb

# 6. Display Live Network Statistics
vnstat -l

# 7. Change the default vnstat output format
vnstat -s (--short)
vnstat --style 0

# 8. Display Top 10 Traffic Days
vnstat --top10

Network related linux commands

nmcli and nmtui (useful for getting DNS IPs)

iwconfig

8 Linux Commands: To Find Out Wireless Network Speed, Signal Strength And Other Information

Getting information (Link Quality, Signal level) about the wireless.

sudo iwconfig

See link quality continuously on screen

watch -n 1 cat /proc/net/wireless

(GUI) NetworkManager

ps -ef | grep NetworkManager

ifconfig - spoof the hardware address at the software level

To change the MAC address temporarily on a NIC (network interface controller),

sudo ifconfig eth0 down
sudo ifconfig eth0 hw ether 00:11:22:33:44:55
sudo ifconfig eth0 up

And it seems there is no need to modify /etc/network/interfaces.

For wlan

sudo ifconfig wlan0 down
sudo ifconfig wlan0 hw ether 00:11:22:33:44:55
sudo ifconfig wlan0 up

See

ip command

It is said ip is replacing the old ifconfig command on modern Linux distributions.

Linux ip Command Examples

http://www.makeuseof.com/tag/networking-commands-linux-terminal/

ip a
ip addr
ip address show

ip link set DEVICE down # eg ip link set eth0 down

ip link set DEVICE up

iptables

route

7 Linux Route Command Examples

  1. Display Existing Routes (route -n)
  2. Adding a Default Gateway (route add default gw 192.168.1.1)
  3. List Kernel’s Routing Cache Information (route -Cn)
  4. Reject Routing to a Particular Host or Network (route add -host 192.168.1.51 reject)
  5. Make 192.168.3.* Accessible from 192.168.1.* (route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.3.10)
  6. Make 192.168.1.* Accessible from 192.168.3.* (route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.10)
  7. Allow Internet Access/External World (route add default gw 125.250.60.59)

On Ubuntu 16.04, it shows

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         FIOS_Quantum_Ga 0.0.0.0         UG    600    0        0 wlp3s0
link-local      *               255.255.0.0     U     1000   0        0 wlp3s0
192.168.1.0     *               255.255.255.0   U     600    0        0 wlp3s0
$ route -n   # showing numerical IP address instead of host name.
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    600    0        0 wlp3s0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlp3s0
192.168.1.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp3s0

Flag value 'U' means up and 'G' means gateway'.

Connect two networks

The trick is explained in this post or the above route command.

For example, my network structure is

  • Modem/router: LAN IP 192.168.1.*/24
  • PC1: connect to Modem/router
  • Second router (ASUS) connect to Modem/router: its WAN IP is 192.168.1.ASUS. It's LAN IP 192.168.2.*/24
  • PC2 (raspberry pi): connect to the second router (ASUS): its IP is 192.168.1.212

By default, PC2 can ssh to PC1 but PC1 cannot access PC2.

The following command will solve the problem that PC1 cannot access PC2:

# From PC1
$ sudo route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.1.ASUS
$ ssh [email protected]    # 192.168.2.212 is the IP address for the Raspberry Pi

$ netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG        0 0          0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 eth0
192.168.2.0     192.168.1.ASUS   255.255.255.0   UG        0 0          0 eth0

One article from linux.com using the ip command.

traceroute

sudo apt-get install traceroute
traceroute 8.8.8.8

On Windows, we can use the tracert command. For example, tracert www.microsoft.com.

nslookup (convert between hostname and ip) and host

$ host google.com
google.com has address 172.217.5.238
google.com has IPv6 address 2607:f8b0:4004:802::200e
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.

$ nslookup google.com
Server:         127.0.1.1
Address:        127.0.1.1#53

Non-authoritative answer:
Name:   google.com
Address: 172.217.7.238
mac$ nslookup cran.r-project.org
Server:		156.40.70.10
Address:	156.40.70.10#53

Non-authoritative answer:
cran.r-project.org	canonical name = cran.wu-wien.ac.at.
Name:	cran.wu-wien.ac.at
Address: 137.208.57.37

mac$ nslookup 137.208.57.37
Server:		156.40.70.10
Address:	156.40.70.10#53

Non-authoritative answer:
37.57.208.137.in-addr.arpa	name = cran.wu-wien.ac.at.

The first two lines show the IP address of my DNS. If we run the command inside a Docker container where DNS was specified manually, the IP address we specified will be shown here.

dig

Dig provided by Google G Suite Toolbox. If the office internet is interrupted, we can use a cell phone to search for the IP address of a website for trouble shooting.

$ sudo apt-get install dnsutils
$ dig world.std.com
; <<>> DiG 9.9.5-3ubuntu0.16-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49227
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;google.com.                    IN      A

;; ANSWER SECTION:
google.com.             130     IN      A       172.217.5.238

;; Query time: 11 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Fri Dec 01 17:32:37 EST 2017
;; MSG SIZE  rcvd: 55

arp (Address Resolution Protocol)

The arp command can be used to show the MAC addresss of all hosts in LAN

arp -a

Check connectivity

Using bash tcp built-ins to test connectivity when nothing else is available:

echo >/dev/tcp/google.com/80; 
if [ $? -eq 0 ]; then echo "Connection Successful"; fi

Find open ports

command example comment
ss sudo ss -tulpn | grep LISTEN contain pid,

add "sudo" can show program/command names on the last column,
Even DietPi includes the ss command

lsof sudo lsof -i -P -n | egrep "PID|LISTEN" sudo is required. Contain pid. Using egrep to include header in output. It includes the command/program names on the first column.

lsof may not be available by default in many OS.

nmap (network mapper) nmap localhost (OR IP) shortest output and input. Need to install. No 'sudo' needed. Works on non local.
netstat

(old 'net-tools' )

netstat -tlpn | grep LISTEN | awk '{print $4 "\t" $7}' show pid and program name. Need to install netstat. Windows already has it.
nc nc -zvw3 <hostname> <port> need to specify a port number. More accurate than nmap. "-w3" means time out after 3 seconds.

What are network interface ports

Understanding Network Interface Ports in Linux. In networking, the term "port" can refer to different concepts depending on the context:

  • Hardware Ports:
  • Software Ports: These are virtual endpoints in an operating system used by network protocols to manage connections. Software ports are identified by a number, ranging from 0 to 65535. For example, port 80 is used for HTTP, and port 443 is used for HTTPS.

Socket

What Are Unix Sockets and How Do They Work

nmap/network mapper - port scanning & IPs in local network

nmap - Network exploration tool and security / port scanner

  • nmap does not show all open ports By default, Nmap scans the most common 1,000 ports for each protocol.
  • https://nmap.org/book/nmap-os-db.html. Local OS database is located at /usr/share/nmap/nmap-os-db. The 2nd line will show the revision number.
    • Modifying the nmap-os-db Database Yourself
    • Download the latest from https://svn.nmap.org/nmap/nmap-os-db. Note that the current revision number has to be found from the website. You can edit the file and insert the revision number on the 2nd line of your local copy.
    • Even I update the database, it cannot detect my Ubuntu 14.04 OS (it only shows OS details: Linux 3.8 - 4.9). For the Raspberry Pi, it can show information from the network adapter; e.g. MAC Address: AA:BB:CC:DD:EE:FF (Raspberry Pi Foundation) but not the OS name (OS details: Linux 3.2 - 4.8).
      sudo mv /usr/share/nmap/nmap-os-db /usr/share/nmap/nmap-os-db-old
      
      cd /usr/share/nmap
      sudo wget https://svn.nmap.org/nmap/nmap-os-db
      
  • http://www.cyberciti.biz/networking/nmap-command-examples-tutorials/
  • http://bencane.com/2013/02/25/10-nmap-commands-every-sysadmin-should-know/
  • http://www.tecmint.com/nmap-command-examples/
    sudo apt-get install nmap
    
    nmap 192.168.1.100   # does not require root privileges
                         # used to check open ports
    
    nmap 192.168.1.*     # show IPs and ports in LAN
    
    sudo nmap -sP 192.168.1.1/24 # show connected IPs (no hostnames?) and MAC addresses
                                 # If you don't use 'sudo' only partial devices can be found
                                 # The output may contains the hostname. For example,
                                 # Nmap scan report for brb-P45T-A.fios-router.home (192.168.1.xxx)
    nmap -sV 192.168.1.1 # show Daemon name (in VERSION column) together with port number
    
    nmap -T4 -F 192.168.1.99-255 # show connected IPs and open ports
                                 # -F means fast
    nmap -F taichimd.us  # Note that domain name != server
    nmap -v taichimd.us
    
    nmap -A 192.168.1.1  # Aggressive scan (more output)
    
    nmap -p http,ssh,mysql taichimd.us  # scan ports/services
                                        # note that mysql will be shown as closed
                                        # ssh port is not correct. 
                                        # Not sure how to get the correct ssh port using nmap
    nmap --open taichimd.us   # scan open ports
    
    sudo nmap -traceroute nih.gov
    
    sudo nmap -sS -O 192.168.1.99 # -O shows operating system
                                  # eth0 MAC
    
    $ nmap localhost # showing the true ports from the server
    
    Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-09 15:01 EDT
    Nmap scan report for localhost (127.0.0.1)
    Host is up (0.00016s latency).
    Not shown: 996 closed ports
    PORT    STATE SERVICE
    22/tcp  open  ssh
    25/tcp  open  smtp
    80/tcp  open  http
    631/tcp open  ipp
    
    $ nmap localhost -p 3838-4000  # Shiny
    
  • A gui version of nmap is called Zenmap. How to install Zenmap Nmap GUI on Ubuntu 20.04 LTS

netstat: get a list of all open ports

How to use netstat in GNU/Linux

  • -l or --listening shows only the sockets currently listening for incoming connection.
  • -a or --all shows all sockets currently in use.
  • -e --show extended/additional information
  • -t or --tcp shows the tcp sockets.
  • -u or --udp shows the udp sockets.
  • -n or --numeric shows the hosts and ports as numbers, instead of resolving in dns and looking in /etc/services.
  • -s --Print network stats
  • -r --Print the network routing information
  • -p --Print PID and name of the program to which each socket belongs
netstat -l             # only listening ports
netstat -rn            # displays the system's routing table
netstat -at
netstat -ant           # For tcp
sudo netstat -pant     # show ports and programs (pant = 喘氣). Best of the best!!!
sudo netstat -peanut   # (output is too wide)
netstat -anp | grep 3306 | wc -l  # print # of connections for the port mysql port

Other commands

sudo lsof -i -P -n | grep LISTEN
sudo ss -tulpn
sudo netstat -tulpn | grep LISTEN
sudo netstat -tulpn   # include dhcpcd & avahi-daemon

ss command

ss is one of 4 commands to check open ports for Linux. The 4 commands are netstat, nmap, ss and lsof.

How to Use the ss Command on Linux

lsof command

How to Use lsof in Linux (With a Practical Example. How to discover what files are currently open and in use on your system?

sudo apt install lsof  # dietpi 

# Basic lsof Output
sudo su
lsof | head -n10

lsof -i   # this gives a more list than nmap command

Common ports

  • List of TCP and UDP port numbers
    • Well-known ports: 0 to 1023
    • Registered ports: 1024 to 49151
    • Dynamic, private or ephemeral ports: 49152–65535
  • A List of Common Ports
  • Replace the default port (such as 22 for ssh) with anyone from 1024-65535 because ports numbers up to 1023 are “well known” ports & should be avoided
  • Some services:

Copy text to a clipboard to be used in other apps

Install the xclip program. See here or here.

sudo apt-get install xclip
# Examples
sort -n -k 3, -k 2 file.txt | xclip -selection clipboard

cat ~/.ssh/id_rsa.pub | xclip -sel clip

Works.

Start Emacs without X

Add -nw (no window) option.

emacs -nw

Audio

Record audio from mic

How to Save Important Voicemails for Both iPhone and Android. Hint: use Audacity.

mp3 codecs

https://help.ubuntu.com/community/RestrictedFormats

sudo apt-get install ubuntu-restricted-extras

Concatenate mp3 files

sudo apt-get install mp3wrap
mp3wrap output.mp3 *.mp3

Reduce the size of an mp3 file

Specify a new lower bitrate using the -b option in lame. For example if your starting mp3 has a quality of 256kbs you can lower its bitrate to 128kbps (or even lower like 64kbps) by:

lame --mp3input -b 128 input.mp3 output.mp3

Convert ogg to mp3

ffmpeg is not included in Ubuntu repository. Use the avconv command. http://superuser.com/questions/15327/how-to-convert-ogg-to-mp3

sudo apt-get install libav-tools
avconv -i input.ogg -c:a libmp3lame -q:a 2 output.mp3

Convert m4a/webm to mp3

avconv -i input.m4a output.mp3

Remove the vocals from any song using Audacity

https://www.makeuseof.com/tag/remove-vocals-song-audacity/

How to Remove Ambient Noise From Audio Files Using Audacity

How to Remove Ambient Noise From Audio Files Using Audacity

Normalize the volume of an audio file

  • Can You Losslessly Increase the Volume of MP3 Files?
  • Use Audacity. To raise (Amplify) volume:
    1. Edit > Select All.
    2. Effect > Amplify. Increase db. Adjust the sound until the highest peaks and lowest valleys of the waveform reach the top and bottom of the window.
    3. Check clip3. Export > MP3 or just start to listen.
  • Command line tool: avconv (replace ffmpeg program). See this post.
avconv -ss 00:00:10 -i OLD.mp3 -vol 2560 NEW.mp3

The anconv/ffmpeg -vol parameter amplifies the sound. The default value is 256 (no amplification), and you can adjust the number accordingly. Here it’s 2560, as it’s 10 times louder. Note that these are not decibel values or anything that sophisticated, but just an integer value. 512 equals to twice the volume, 768 three times, 1024 four times, etc. The -ss parameter specifies the start time offset. Here it will skip the first 10 seconds.

I found the converted file by sox has about one half file size compared to anconv/ffmpeg program (source file=47MB, anconv converted=135MB, sox converted file=54MB).

sudo apt-get install sox libsox-fmt-all
sox --norm OLD.mp3 NEW.mp3 trim 10
sox --norm OLD.mp3 NEW.mp3 silence 1 0.1 1%
sox -v 4.0 OLD.mp3 NEW.mp3             # increase volume 

where '--norm' will normalize the audio and the 'trim' option set to skip the first 10 seconds. The silence parameter allows to trim silence at the beginning without a need to specify the number of seconds.

cut, delete or trim an audio

  1. Open the audio file in audacity.
  2. select a region in the waveform area. Do not select in the time interval area (above the waveform).
    1. To precisely select a range from one position to the end. Click Zoom in several times. Click one position in the waveform and click Edit -> Select -> Cursor to the track end to select
    2. Similarly, if we want to precisely select a range from the start to some position, we can click one position in the waveform and then click Edit -> Select -> Track start to cursor.
    3. To move around the track, use the scrollbar (below the waveform and above the bottom toolbar, not quite clear in Ubuntu/Unity)
  3. Click Edit -> Remove Audio or labels -> Cut/Delete/Trim Audio
  4. play the new audio by clicking the green triangle.
  5. File -> Export -> mp3 format.

Helpful resource for Audacity.

  1. Different Toolbars
  2. Tutorial - Editing an Existing Audio File

Fade out at the end of an audio

  1. Select a region.
  2. Effect -> Fade out

Wireshark

sudo apt-get install wireshark
sudo chmod 4711 `which dumpcap`

Track the Time a Command Takes

How To Find The Execution Time Of A Command Or Process In Linux

time command

time COMMAND
time (COMMAND1; COMMAND2)
time (COMMAND1 && COMMAND2)

help time

When I run a set of 7 jobs using parallel, time command gives an output

real  15m53.788s # the wall clock time the command took from execution till termination
user  95m20.238s # the time taken by the user space
sys   9m1.320s   # the time taken by kernel space

Here we see the real time is about 16m and the user time is about 6-7 times the real time. Indicating the parallel executing works.

/usr/bin/time command

/usr/bin/time provides more information then time command.

man time

Magazines

Latex

Editors

Online editing

  • Latex Base. You can start to try it without registration. Free accounts cannot publish but still can download.
  • Overleaf. Free account for 1GB space.
  • ShareLatex

Missing cls

$ apt-cache search IEEEtran
texlive-publishers - TeX Live: Publisher styles, theses, etc.
sudo apt-get install texlive-publishers

Missing sty

$ apt-cache search pseudocode
gpt - G-Portugol is a portuguese structured programming language
libgportugol-dev - Development files for the G-Portugol library
libgportugol0 - G-Portugol library
texlive-science - TeX Live: Natural and computer sciences
$ sudo apt-get install texlive-science

PDF

See PDF.

Flow chart

  • LibreOffice Draw OR MS_PowerPoint (insert > shape). Check youtube.
  • yEd
  • Dia & wikipedia
  • (online) www.draw.io

Clock

xclock (analog)

oclock -geometry 500x500+100+0 &

oclock (analog)

oclock -bg blue -geometry 500x500+100+0 -bd purple -transparent &
oclock -bg blue -geometry 500x500+100+0 -bd purple -jewel green &

See oclock, X - a portable, network-transparent window system which includes an example of specifying the geometry parameter.

dclock (digital)

Digital clock for the X Window System with flexible display.

sudo apt-get install dclock
dclock -h
dclock -d
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139         # 'q' to quit
dclock -date "Today is %m/%d/%y" -led_off black -bg black -fg yellow -geometry 400x150+0+0 # width x hight + X + Y

In practice, I create a shell script file <bin/clock> with the following content. The first ampersand sign is to hide warnings messages and the 2nd ampersand sign is to put the process in the background.

dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139 &>/dev/null &

Lubuntu digital clock format

http://netgator.blogspot.com/2012/09/change-edit-panel-digital-clock-format.html. My format is

%a, %x, %r
# Tue, 05/17/2016, 09:42:27 PM

%a %m-%d-%y, %I:%M %p
# Mon 05-30-16, 08:31 AM

xdaliclock (digital)

https://www.mankier.com/1/xdaliclock

Scaling is not good. Colors is changing with time.

xdaliclock -noseconds -cycle  # 'q' to quit

date command

sudo apt install toilet
sudo apt install figlet
watch -n 60 "date +'%m/%d/%y   %H:%M:%S' | toilet"

ls /usr/share/figlet # list of fonts
                     # looking for *.tlf
date +'%m/%d/%y%H:%M:%S' | toilet -f mono12
date +'%m/%d/%y%H:%M:%S' | toilet -f bigmono12   # good on 1024x600
date +'%m/%d/%y%H:%M:%S' | toilet -f bigascii12
date +'%m/%d/%y%H:%M:%S' | toilet -f ascii12

watch --color "date +'%m/%d/%y%H:%M:%S' | toilet -f bigmono12 -F metal"

while true; do echo "$(date '+%H:%M:%S' | toilet -f bigmono12 -F border --metal)"; sleep 1; done

Reminder take a break, relieve eye strain

Stretchly. It's open-source and cross-platform. Nodejs is required.

Workrave is another choice. The source code is available too.

Prevent Eye Strain While Working On Your Linux Desktop With Safe Eyes, Github source code

wine

Wine

Running Linux in the AWS/Amazon Web Services

Forum software

RAID

Timer

How to track you laptop using Prey

https://www.howtoforge.com/tutorial/how-to-track-your-linux-laptop/

last command

Linux last Command Tutorial for Beginners (8 Examples)

Display a list of system shutdown/reboot date/time

Linux Find Out Last System Reboot Time and Date Command

# Works on Linux and Mac
last shutdown
last reboot

Automatic reboot after power failure

It seems there is no reliable way to find out when the power failed.

The linux command 'last' can show some information about system reboot.

Another way is to modify the BIOS to select the option like 'Power off and Reboot'. This won't automatically boot your computer when it is shutdown normally.

How to restart/shutdown server safely

How to restart CentOS or RHEL server safely

Wake up and Shut Down Linux Automatically

Two best options

  • Bios: BIOS may have an easy-to-use wakeup scheduler
  • wakeonlan:
    • Eanble it: Check if it is enabled by default. If not, we can 1) enable it through a command (ethtool -s eth0 wol g) or 2) using the Network Manager
    • Send a wake up command: (from a second linux) /usr/bin/wakeonlan D0:50:99:82:E7:2B where D0:50:99:82:E7:2B is the IP on the machine you want to wake it up

BIOS

Find out BIOS version

Linux Find Out BIOS Version Using a Command Line Option

How to update Lenovo BIOS from Linux without using Windows

https://www.cyberciti.biz/faq/update-lenovo-bios-from-linux-usb-stick-pen/

Internet speed test

Web

Speedtest-cli

See Track_Internet_Dropouts.

sudo apt-get intall python-pip
sudo pip install speedtest-cli
# A slightly modified code that will create a one-line space/semi-colon 
# delimited result is 
git clone https://github.com/HenrikBengtsson/speedtest-cli-extras.git

speedtest-cli-extras/bin/speedtest-csv

works. But if I want to put it in cron, cron will issue an error speedtest-cli cannot be found. So I need to modify line 52 of the code in <speedtest-cli-extras/bin/speedtest-csv> to explicitly specify the location of speedtest-cli.

    /usr/local/bin/speedtest-cli --share > $log

NOTE: 1. the results differ from the network connection. For example, the speed is good when I test it on the machine directly connected to the router. 2. It is helpful to modify the last line of the bash script to output what I need. 3. The separator is ";" in the output.

curl and wget

How to Run Speed Test from the Command Line to Check Internet Connection Speed

uname - Print system information

uname -a will give you

  • OS (uname = uname -s if you are under a Linux environment)
  • OS (uname -s) eg Linux
  • node name (uname -n=hostname)
  • kernel release (uname -r) eg 3.16.0-38-generic
  • kernel version (uname -v)
  • machine architecture (uname -m) eg x86_64
  • processor (uname -p)
  • hardware platform (uname -i)
  • operating system (uname -o)

How to check if running in Cygwin, Mac or Linux?

Hardware information

Command Line

hwinfo

https://www.2daygeek.com/python-hwinfo-check-display-system-hardware-configuration-information-linux/

On Ubuntu, use sudo apt install -y hwinfo to install hwinfo. Install hwinfo on Ubuntu 20.04

dmesg command

How to Use the dmesg Command on Linux

sudo dmesg -L -T
sudo dmesg -L -T --follow   # Watching Live Events
sudo dmesg -L -T | grep -i usb    # Search for a specific term
sudo dmesg | grep -E "memory|tty|dma"  # Search for multiple terms

where -L to is force color output and -T is to make timestamp human-readable.

Linux Logo and the current system information

odroid@odroid:~$ sudo apt-get install screenfetch
odroid@odroid:~$ screenfetch
                          ./+o+-       odroid@odroid
                  yyyyy- -yyyyyy+      OS: Ubuntu 15.10 wily
               ://+//////-yyyyyyo      Kernel: armv7l Linux 3.10.96-77
           .++ .:/++++++/-.+sss/`      Uptime: 4d 23h 8m
         .:++o:  /++++++++/:--:/-      Packages: 2000
        o:+o+:++.`..```.-/oo+++++/     Shell: 2263
       .:+o:+o/.          `+sssoo+/    Resolution: 1920x1080
  .++/+:+oo+o:`             /sssooo.   DE: MATE 1.10.2
 /+++//+:`oo+o               /::--:.   WM: Metacity (Marco)
 \+/+o+++`o++o               ++////.   GTK Theme: 'Ambiant-MATE' [GTK2/3]
  .++.o+++oo+:`             /dddhhh.   Icon Theme: Ambiant-MATE
       .+.o+oo:.          `oddhhhh+    Font: Ubuntu 10
        \+.++o+o``-````.:ohdhhhhh+     CPU: ARMv7 rev 3 (v7l) @ 1.4GHz
         `:o+++ `ohhhhhhhhyo++os:      GPU: Gallium 0.4 on llvmpipe (LLVM 3.6, 128 bits)
           .o:`.syhhhhhhh/.oo++o`      RAM: 537MiB / 1990MiB
               /osyyyyyyo++ooo+++/    
                   ````` +oo+++o\:    
                          `oo++.      

odroid@odroid:~$ screenfetch -h

Neofetch.png

Dictionary - Artha

  • Lifehacker. Once it is launched, it is sitting on the task bar. Press Ctrl+Alt+W after selecting a word to look it up in Artha (a balloon tip will pop up on the screen top-right). It also supports using regular expressions to search words.
sudo apt-get install artha

Translation

odroid@odroid:~/binary$ ./trans :zh-TW word
word
/wərd/

字
(Zì)

Definitions of word
[ English -> 正體中文 ]

noun
    字
        word, character, letter, calligraphy, symbol, style of writing
    詞
        word, term, speech, statement
    單詞
        word, individual word
    話
        words, word, dialect, saying, talk, speech
    言
        word, speech, character
    言辭
        words, word, what one says
    筆墨
        pen and ink, words, word, writings
    約言
        pledge, promise, word

verb
    為 ... 措辭
        word
odroid@odroid:~/binary$ time ./trans -brief :zh-TW word
字

real	0m4.249s
user	0m2.670s
sys	0m1.330s

ASCII art/ word art

  ____  ____  ____       ____            _____           _     
 | __ )|  _ \| __ )     / ___|  ___  __ |_   _|__   ___ | |___ 
 |  _ \| |_) |  _ \ ____\___ \ / _ \/ _` || |/ _ \ / _ \| / __|
 | |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
 |____/|_| \_\____/     |____/ \___|\__, ||_|\___/ \___/|_|___/
                                       |_|                     
  ____  _____  ____        _____         _______          _     
 |  _ \|  __ \|  _ \      / ____|       |__   __|        | |    
 | |_) | |__) | |_) |____| (___   ___  __ _| | ___   ___ | |___ 
 |  _ <|  _  /|  _ <______\___ \ / _ \/ _` | |/ _ \ / _ \| / __|
 | |_) | | \ \| |_) |     ____) |  __/ (_| | | (_) | (_) | \__ \
 |____/|_|  \_\____/     |_____/ \___|\__, |_|\___/ \___/|_|___/
                                         | |                    
                                         |_|                    
  ___ ___ ___     ___          _____         _    
 | _ ) _ \ _ )___/ __| ___ __ |_   _|__  ___| |___
 | _ \   / _ \___\__ \/ -_) _` || |/ _ \/ _ \ (_-<
 |___/_|_\___/   |___/\___\__, ||_|\___/\___/_/__/
                             |_|                  

Install And Manage Software From Source

How To Install And Manage Software From Source Using GNU Stow In Linux

Software that scan Malware and rootkits

Text to speech

VPN

Ubuntu -> VPN

Mono Project

Mono is a software platform designed to allow developers to easily create cross platform applications part of the .NET Foundation

Mono is required for Repetier-Host software for 3D printing.

NAS server

OpenMediaVault

OpenMediaVault

FreeNAS

ZFS system (FreeBSD-based).

10 Reasons Why You Should Store Your Data on a FreeNAS Box. Note With the current version of FreeNAS (FreeNAS 11) comes a hypervisor. See

Change detection

http://bhfsteve.blogspot.com/2013/03/monitoring-web-page-for-changes-using.html

3 command-line tools for feigning productivity

https://opensource.com/article/18/2/command-line-tools-productivity: Blessed-contrib (javascript), Genact, Hollywood.

Mind mapping

Diagram

Open source surveillance

ZoneMinder

Systemctl, systemd

Systemd vs SysVinit

Systemctl vs service commands

What is the difference between service and systemctl? service is an "high-level" command used for starting and stopping services in different unixes and linuxes. Depending on the "lower-level" service manager, service redirects on different binaries. For example, on CentOS 7 it redirects to systemctl.

$ service nginx start
# VS
$ systemctl start nginx

$ systemctl   # list all services
$ cat /lib/systemd/system/rsyslog.service
$ systemctl status rsyslog
$ cat /lib/systemd/system/ufw.service

How to Run a Linux Program at Startup with systemd

How Long Does it Take To Boot Your Linux System

Find Out How Long Does it Take To Boot Your Linux System

$ systemd-analyze       # total boot time along with the time taken by 
                        # firmware, boot loader, kernel and the userspace
$ systemd-analyze blame # breakdown the boot time into each unit

Check if Your Linux System Uses systemd

How to Check if Your Linux System Uses systemd

chkservice

chkservice Is A systemd Unit Manager With A Terminal User Interface

Kernel

Firmware update

Fwupd 1.9.9 Released with Support for Lenovo X1 Yoga Gen7 530E 2-in-1 Laptops

Game

See Game.

Best Linux Adobe Alternatives You Need to Know

Linux distributions

Linux Distribution

chroot

Chroot