Linux: Difference between revisions

From 太極
Jump to navigation Jump to search
(642 intermediate revisions by 2 users not shown)
Line 1: Line 1:
__FORCETOC__
= man =
=== 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]
==== Navigation ====
* [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.
 
== Navigation ==
[https://wiki.gentoo.org/wiki/Man_page/Navigate Gentoo] and [https://fossbytes.com/linux-lexicon-man-pages-navigation/ fossbytes]
[https://wiki.gentoo.org/wiki/Man_page/Navigate Gentoo] and [https://fossbytes.com/linux-lexicon-man-pages-navigation/ fossbytes]


Line 10: Line 14:
* q – Quit
* q – Quit


==== Search within a man page ====
== Search within a man page ==
Use / and type your search pattern.
Use / and type your search pattern.


Use 'n' for forward search and 'N' for reverse search.
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]
Regular expression is supported. For example to find all of the long arguments with: /(--)[a-Z]


==== Search from all man pages ====
== Colored man pages ==
<span style="color: red">This is a cool tip!</span>
 
By default, the man program normally uses a terminal '''pager''' program such as '''less''' to format its output.
 
[https://www.tecmint.com/view-colored-man-pages-in-linux/ Add the following to "~/.bashrc" file]
<pre>
<pre>
man -k KEYWORD
export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'
</pre>
 
(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].
 
== Navigate to another man page within a man page ==
See [https://stackoverflow.com/a/38604548 here].
 
When inside the man page, press ! followed by a valid shell command.
 
For example : !man cat
 
== View a specific "Section" ==
* [https://unix.stackexchange.com/a/3587 What do the numbers in a man page mean?]
* [https://superuser.com/questions/357048/how-do-you-switch-between-linux-manual-pages How do you switch between Linux manual pages?]
 
{{Pre}}
$ whatis printf
printf (1)          - format and print data
printf (3)          - formatted output conversion
Printf (3o)          - Formatted output functions.
$ man 3 printf
</pre>
</pre>
will give you a list of all man pages which relate to 'KEYWORD'.


==== TLDR pages: alternative to Man ====
== Read man pages in vi without using temporary files ==
[https://fossbytes.com/tldr-pages-linux-man-pages-alternative/ TLDR pages: Simplified Alternative To Linux Man Pages]
[https://stackoverflow.com/a/16740302 What is a way to read man pages in vim without using temporary files]
{{Pre}}
man find | vi -
</pre>


=== Some books ===
== 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 ==
<ul>
<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>
</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>
 
== Cheat.sh (better than TLDR) ==
[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.
{{Pre}}
curl cheat.sh/tar
 
curl cht.sh/python/random+list # Python programming language cheat sheet for random list
</pre>
My test shows cheat.sh can find more commands and it gives colored output.
 
= Some books =
* UNIX in a nutshell
* UNIX in a nutshell
* sed & awk
* sed & awk
Line 45: Line 117:
* [https://opensource.com/article/18/5/list-books-Linux-open-source 17 books for Linux and open source fans]
* [https://opensource.com/article/18/5/list-books-Linux-open-source 17 books for Linux and open source fans]


=== Beautiful desktop ===
= Beautiful desktop =
* http://lifehacker.com/the-aincrad-desktop-1732684767
* http://lifehacker.com/the-aincrad-desktop-1732684767
* http://lifehacker.com/the-distant-pyramid-desktop-1654404411
* http://lifehacker.com/the-distant-pyramid-desktop-1654404411
Line 51: Line 123:
* http://lifehacker.com/the-midsummer-nights-desktop-1704207155
* http://lifehacker.com/the-midsummer-nights-desktop-1704207155


==== .desktop file ====
== .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 [https://www.maketecheasier.com/albert-launcher-linux/ Albert Launcher].
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].


Line 61: Line 133:
* /usr/share/applications
* /usr/share/applications


==== List of installed desktop environment ====
== List of installed desktop environment ==
<pre>
<pre>
ls -l /usr/share/xsessions/
ls -l /usr/share/xsessions/
</pre>
</pre>


==== Themes ====
== Themes ==
[https://www.maketecheasier.com/best-linux-dark-themes/ 5 of the Best Linux Dark Themes that Are Easy on the Eyes]
[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 ===
= Virtual consoles/virtual terminals =
Linux allows ''virtual consoles'' (aka ''virtual terminals'') to be opened while an ''X Window System'' is executing.
Linux allows ''virtual consoles'' (aka ''virtual terminals'') to be opened while an ''X Window System'' is executing.


Line 76: Line 148:
[https://opensource.com/article/16/11/managing-devices-linux Managing devices in Linux] -> Fun with device files.
[https://opensource.com/article/16/11/managing-devices-linux Managing devices in Linux] -> Fun with device files.


==== Change console fonts ====
== Change/increase console fonts ==
https://www.linux.com/learn/intro-to-linux/2018/1/how-change-your-linux-console-fonts
* https://www.linux.com/learn/intro-to-linux/2018/1/how-change-your-linux-console-fonts
* https://youtu.be/LOg4xfDQafc


=== Desktops/Workspaces ===
= Desktops/Workspaces =
'''Ctrl + Alt + ->''' or '''Ctrl + Alt + <-''' to switch workspaces.
'''Ctrl + Alt + ->''' or '''Ctrl + Alt + <-''' to switch workspaces.


Line 90: Line 163:
[https://www.lifewire.com/complete-list-of-linux-mint-4064592 Complete List of Linux Mint 18 Keyboard Shortcuts for Cinnamon] for more examples.
[https://www.lifewire.com/complete-list-of-linux-mint-4064592 Complete List of Linux Mint 18 Keyboard Shortcuts for Cinnamon] for more examples.


=== Virtual memory ===
= Mouse =
[http://www.2daygeek.com/linux-vmstat-command-examples-tool-report-virtual-memory-statistics/ '''vmstat''' – A Standard Nifty Tool to Report Virtual Memory Statistics]
[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)]


==== hcache ====
= Virtual memory =
 
== vmstat ==
* [http://www.2daygeek.com/linux-vmstat-command-examples-tool-report-virtual-memory-statistics/ '''vmstat''' – A Standard Nifty Tool to Report Virtual Memory Statistics]
* [https://www.howtogeek.com/424334/how-to-use-the-vmstat-command-on-linux/ How to Use the vmstat Command on Linux]
 
== hcache ==
A tool fork from pcstat, with a feature that showing top X biggest cache files globally
A tool fork from pcstat, with a feature that showing top X biggest cache files globally
* https://github.com/silenceshell/hcache
* https://github.com/silenceshell/hcache
* http://www.datastart.cn/tech/2017/05/20/hcache.html
* http://www.datastart.cn/tech/2017/05/20/hcache.html


=== Memory ===
= Memory: free command =
[https://www.makeuseof.com/tag/manage-linux-ram/ Is Linux Eating Your RAM? How to Manage Your Memory]
* [https://www.makeuseof.com/tag/manage-linux-ram/ Is Linux Eating Your RAM? How to Manage Your Memory]
* [https://www.howtogeek.com/456943/how-to-use-the-free-command-on-linux/ How to Use the free Command on Linux] (*detailed and comprehensive)
* [https://www.howtogeek.com/659529/how-to-check-memory-usage-from-the-linux-terminal/ How to Check Memory Usage From the Linux Terminal]


Three types of memory reported by the '''free''' command.
Three types of memory reported by the '''free''' command.
* Used: RAM that is currently in use by an application.
* 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.
* 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.'''
* Shared: Amount of memory used by the tmpfs file systems.
* Free: RAM that is not in use by an application or disk caching.
* 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
How to Clear RAM Memory Cache and Buffer
<syntaxhighlight lang='bash'>
{{Pre}}
# To clear pagecache, enter the following command:
# To clear pagecache, enter the following command:
echo 1 > /proc/sys/vm/drop_caches
echo 1 > /proc/sys/vm/drop_caches
Line 116: Line 199:
# To clear pagecache, dentries, and inodes all together, change the number to 3:
# To clear pagecache, dentries, and inodes all together, change the number to 3:
echo 3 > /proc/sys/vm/drop_caches
echo 3 > /proc/sys/vm/drop_caches
</syntaxhighlight>
</pre>
 
== How do I determine the number of RAM slots in use ==
<pre>
sudo dmidecode -t memory
</pre>
 
== Logging memory ==
* [[#System_monitor_tools_.28GUI.29 | Linux system monitor tools]] where [http://sebastien.godard.pagesperso-orange.fr/documentation.html Sysstat] package can be used.
* [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?]
* [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'''


=== ps, pgrep and pidof: How much resource is used by a process ===
== Shows Per-Program Memory Usage On Linux ==
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
* '''atop''' command. '''atop -m''' and press p (per program). Look at the 'RSIZE' column.
<syntaxhighlight lang='bash'>
** [https://unix.stackexchange.com/a/209915 Sum the memory usages of all the processes of a program?]
ps -p <pid> -o %cpu,%mem,cmd
** [https://www.redhat.com/sysadmin/analyzing-linux-server-performance-atop  Analyzing Linux server performance with atop]
</syntaxhighlight>
** [https://haydenjames.io/use-atop-linux-server-performance-analysis/ atop – For Linux server performance analysis]
For example,
* [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.
<syntaxhighlight lang='bash'>
* '''ps_mem''': https://www.linuxuprising.com/2019/04/psmem-shows-per-program-memory-usage-on.html.
$ ps -ef | grep akregator
{{Pre}}
brb      15013  1942  1 10:41 ?        00:00:05 akregator --icon akregator -caption Akregator
$ pip install ps_mem
brb      15186 24045  0 10:50 pts/11  00:00:00 grep --color=auto akregator
$ ps_mem -p $(pgrep -d, -u $USER)
$ ps -p 15013 -o %cpu,%mem,cmd
Private  +  Shared  =  RAM used Program
%CPU %MEM CMD
...
1.0  0.8 akregator --icon akregator -caption Akregator
249.9 MiB +  43.9 MiB = 293.9 MiB firefox
</syntaxhighlight>
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>
 
== Check RAM information ==
* [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
* [https://www.binarytides.com/linux-command-check-memory-usage 5 commands to check memory usage on Linux]
{{Pre}}
sudo dmidecode -t memory
 
sudo dmidecode -t 17
</pre>


'''pgrep'''
== Free up memory ==
<syntaxhighlight lang='bash'>
[https://www.makeuseof.com/improve-performance-free-up-ram-on-linux/ How to Free Up Memory and Improve RAM Performance on Linux]
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 -contentproc -childID 1 -isForBrowser -prefsLen 17405 -schedulerPrefs 0001,2 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 25486 true tab
brb      25961 25486  0 Sep10 ?        00:41:50 /usr/lib/firefox/firefox -contentproc -childID 4 -isForBrowser -prefsLen 20505 -schedulerPrefs 0001,2 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 25486 true tab
brb      27951 25486  0 Sep10 ?        01:35:41 /usr/lib/firefox/firefox -contentproc -childID 7 -isForBrowser -prefsLen 20570 -schedulerPrefs 0001,2 -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 25486 true tab
08:49AM ~$ pgrep firefox
25486
</syntaxhighlight>


'''pidof'''
== Monitor Memory Utilization And Send an Email ==
<syntaxhighlight lang='bash'>
* [https://www.2daygeek.com/linux-bash-script-to-monitor-memory-utilization-usage-and-send-email/ Bash Script to Monitor Memory Usage on Linux]
08:49AM ~$ pidof firefox
* [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.
27951 25961 25612 25486
* [https://www.cloudsavvyit.com/1230/getting-started-with-monit-for-server-monitoring/ Getting Started with Monit for Server Monitoring]
08:51AM ~$ pidof /usr/lib/firefox/firefox
27951 25961 25612 25486
</syntaxhighlight>


=== All You Need To Know About Processes in Linux ===
== zram ==
http://www.tecmint.com/linux-process-management/
[https://opensource.com/article/22/11/zram-swap-linux rop swap for zram on Linux]


=== [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] ===
= [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] =


# Run upgrade such as '''apt-get update; apt-get upgrade'''. It helps to resolve the unmet dependencies issue too.
# Run upgrade such as '''apt-get update; apt-get upgrade'''. It helps to resolve the unmet dependencies issue too.
Line 165: Line 267:
# Install ClamAV / Clamtk antivirus
# Install ClamAV / Clamtk antivirus


=== Query whether the OS is 64-bit or 32-bit ===
= Query whether the OS is 64-bit or 32-bit =
<pre>
<pre>
SYSTEM_ARCH=getconf LONG_BIT
SYSTEM_ARCH=getconf LONG_BIT
Line 171: Line 273:
</pre>
</pre>


=== Switch user in command line ===
= Command line improved =
use <pre>su newusername</pre> to switch to another user.
 
=== Command line improved ===
https://remysharp.com/2018/08/23/cli-improved
https://remysharp.com/2018/08/23/cli-improved


=== Directory permission / attribute ===
= Directory permission / attribute =
See http://unix.stackexchange.com/questions/21251/how-do-directory-permissions-in-linux-work
See http://unix.stackexchange.com/questions/21251/how-do-directory-permissions-in-linux-work


Line 188: Line 287:
When we create a new directory, the attribute is 775. Some pre-created directories (Desktop, Documents, Music, Pictures, Public) have an attribute 755.
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 ===
= Making a new temporary directory =
https://www.howtoforge.com/linux-mktemp-command/  
https://www.howtoforge.com/linux-mktemp-command/  
<syntaxhighlight lang='bash'>
{{Pre}}
mktemp  # temp directory is under /tmp
mktemp  # temp directory is under /tmp
mktemp -d tempdirXXX # temp directory is under the current directory
mktemp -d tempdirXXX # temp directory is under the current directory
mktemp tempfileXXX # temp file under the current directory
mktemp tempfileXXX # temp file under the current directory
</syntaxhighlight>
</pre>
 
= Shell =
== Login shell and non-login shell ==
Login Shell
# /etc/profile
# /etc/profile.d/*.sh
# ~/.bash_profile or ~/.profile (for example, environment variable like PATH)
# ~/.bashrc
# /etc/bashrc
# ~/.bashrc
 
Non-Login shell
# ~/.bashrc
# /etc/bash.bashrc or /etc/bashrc
# ~/.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''.


=== Special permissions ===
=== Aliases and Functions for Individual Users ===
* [https://www.linux.com/learn/understanding-linux-file-permissions Understanding Linux File Permissions]
# /etc/profile (systemwide environment and shell variables)
* [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]
# /etc/profile.d/*.sh (systemwide environment and shell variables)
# ~/.bash_profile (user '''environment and shell variables''')
# ~/.bashrc (executes /etc/bashrc)
# /etc/bashrc (systemwide aliases and shell functions)
# ~/.bashrc (user '''aliases''' and shell functions)


'''s''' bit - setuid, getuid
=== 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.


=== Shell ===
On raspbian commenting out some lines does help. Interestingly, the same lines does not make any difference on x86 server.
==== 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.  
== the source command ==
<syntaxhighlight lang='bash'>
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.
sudo su -
 
# OR
== login shell (.bash_profile) vs interactive shell (.bashrc) ==
* http://stackoverflow.com/questions/18186929/differences-between-login-shell-and-interactive-shell
* [https://linuxtldr.com/interactive-login-and-non-login-shell/ What is Interactive Login and Non-Login Shell]
* 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. 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.
 
To determine the shell type: '''echo $-'''
 
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'''.
 
=== /root/.bashrc ===
If we use "sudo SOME_COMMAND", ''~/.bashrc'' won't work. In this case, we have to
# run "sudo su"
# Edit '''/root/.bashrc'''
 
== Login banner ==
[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'''
 
== 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.  
{{Pre}}
sudo su -
# OR
sudo su
sudo su
# OR
# OR
sudo -s
sudo -s
</syntaxhighlight>
</pre>
This can be useful when running 'su' or 'su -' failed because of an authentication failure error (note Ubuntu locked the root account).  
This can be useful when running 'su' or 'su -' failed because of an authentication failure error (note Ubuntu locked the root account).  


Line 219: Line 371:


For sudo to work, my account ('debian' in this case) has to be included in the config file '''/etc/sudoers'''.
For sudo to work, my account ('debian' in this case) has to be included in the config file '''/etc/sudoers'''.
<syntaxhighlight lang='bash'>
{{Pre}}
debian  ALL=NOPASSWD: ALL
debian  ALL=NOPASSWD: ALL
</syntaxhighlight>
</pre>
When sudo is invoked, it asks for the password of the user who started it.
When sudo is invoked, it asks for the password of the user who started it.


==== Switch to another user and run a command ====
== pinky: find out about the people logged on to your Linux computer ==
* [https://www.cyberciti.biz/open-source/command-line-hacks/linux-run-command-as-different-user/ Linux Run Command As Another User]
[https://www.howtogeek.com/427004/how-to-use-the-pinky-command-on-linux/ How to Use the pinky Command on Linux]
 
== su: Switch to another user and run a command ==
<ul>
<li>su means 'substitute user'.
<li>Use <pre>su newusername</pre> to switch to another user.
<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
'''runuser -l''' command
<syntaxhighlight lang='bash'>
{{Pre}}
runuser -l  userNameHere -c 'command'
runuser -l  userNameHere -c 'command'
</syntaxhighlight>
</pre>


'''su -''' command (keep the dash sign after su)
<li>'''su -''' command (keep the dash sign after su)
* su means 'substitute user'.
<li>http://unix.stackexchange.com/questions/156343/pass-arguments-to-a-command-run-by-another-user
* http://unix.stackexchange.com/questions/156343/pass-arguments-to-a-command-run-by-another-user
<li>http://unix.stackexchange.com/questions/87860/how-does-this-su-c-command-seem-to-pass-two-commands-instead-of-one
* http://unix.stackexchange.com/questions/87860/how-does-this-su-c-command-seem-to-pass-two-commands-instead-of-one
{{Pre}}
<syntaxhighlight lang='bash'>
su - username -c 'command'
su - username -c 'command'


Line 248: Line 405:


man su
man su
</syntaxhighlight>
</pre>
</ul>


==== What’s the Difference Between Bash, Zsh, and Other Linux Shells ====
== Keyboard shortcut to move cursor in the terminal ==
https://www.howtogeek.com/68563/htg-explains-what-are-the-differences-between-linux-shells/
* Alt + b: go left (back) one word
* Alt + f: go forward on word


==== Bash shell programming ====
Example: cd ~/bitbucket/gbmpdx/annovar_biowulf  (Now press Alt+b to see the cursor moves)
http://bash.cyberciti.biz/guide/Main_Page


==== [https://fishshell.com/ Fish shell] ====
== Record terminal session to a text file ==
[https://www.ostechnix.com/oh-fish-make-shell-beautiful/ Oh My Fish! Make Your Shell Beautiful]
<pre>
script history_log.txt
# recording begins
exit # stop recording
</pre>
This will include everything showing on your screen.


==== Tools To Record Your Terminal And Generate Animated Gif or SVG Images ====
== Tools To Record Your Terminal And Generate Animated Gif or SVG Images ==
* [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]
=== Asciinema & agg ===
* [https://www.2daygeek.com/termtosvg-record-your-terminal-sessions-as-svg-animations-in-linux/# Termtosvg – Record Your Terminal Sessions As SVG Animations In Linux]
* It works on Ubuntu 23.04
* [https://github.com/asciinema/asciinema Asciinema]
** [https://www.2daygeek.com/linux-asciinema-record-your-terminal-sessions-share-them-on-web/ Asciinema – Record and Share your terminal sessions on the fly]
* [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.


=== Redirect standard error ===
Consider adding shell completions for pipx. Run 'pipx completions' for
http://bash.cyberciti.biz/guide/Standard_error. Use '''2>''' operator.
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!
</pre>
Open another tab
<pre>
<pre>
command 2> errors.txt
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>
</pre>


=== Quotes and asterisk ===
=== terminalizer ===
Combining these two will not work. For example
* 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]
** [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>
 
=== Termtosvg ===
(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]
 
== Record and Replay Linux Terminal Sessions Activity: script ==
[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
 
== 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.
<pre>
command 2> errors.txt
</pre>
 
== Redirect standard output ==
This can be used in the cron job or displaying a clock on the desktop.
<pre>
$ cat ~/bin/clock
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139  &>/dev/null &
</pre>
 
= Quotes and asterisk =
Combining these two will not work. For example
{{Pre}}
brb@T3600 ~ $ ls -l ~/GSE48215/*.fastq
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_1.fastq
Line 279: Line 509:
brb@T3600 ~ $ ls -l "~/GSE48215/*.fastq"
brb@T3600 ~ $ ls -l "~/GSE48215/*.fastq"
ls: cannot access ~/GSE48215/*.fastq: No such file or directory
ls: cannot access ~/GSE48215/*.fastq: No such file or directory
</syntaxhighlight>
</pre>
 
= 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>
 
= ls command =
List Files With Detailed Information from [https://www.makeuseof.com/ls-command-linux/ How to Use the ls Command in Linux]


=== ls command ===
To use UID/GID instead of the user name and group name in '''ls -l''', use the '''-n''' option.
To use UID/GID instead of the user name and group name in '''ls -l''', use the '''-n''' option.
<pre>
<pre>
Line 295: Line 536:
</pre>
</pre>


=== cp command ===
== Follow the symbolic link ==
[https://www.howtoforge.com/linux-cp-command/ Linux cp command tutorial for beginners (8 examples)]
Use '''-H''' option
{{Pre}}
ls -lH myDir
</pre>


==== copy a directory ====
== List only directories ==
<syntaxhighlight lang='bash'>
<pre>
cp -avr Dir1 Dir2
ls -d */               # current directory
</syntaxhighlight>
ls -ld ~/Downloads/*/  # ~/Downloads
where -a will preserve the attributes of files/directories, -v means verbally and -r means copy the directory recursively.
ls -l -d */
</pre>


=== Copy a file with progress bar with '''pv''' (plus how to eject the USB drive) ===
== List only files ==
http://www.tecmint.com/monitor-copy-backup-tar-progress-in-linux-using-pv-command/
<pre>
ls -l | egrep -v '^d'
</pre>


<syntaxhighlight lang='bash'>
== Find and Delete Broken Symbolic Links ==
sudo apt-get install pv
<pre>
pv file1 > file2    # don't forget the ">" operator and the destination is a file, not a directory
find /path/to/directory -xtype l -delete
</syntaxhighlight>
</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.
== Special characters, escape ==
<syntaxhighlight lang='bash'>
[https://stackoverflow.com/a/19177228 List of characters which needs to be escaped in a linux shell command]
sudo apt-get install udisks


sudo udisks --unmount /dev/sdb1  # /dev/sdb1 is the partition
<pre>
sudo udisks --detach /dev/sdb    # /dev/sdb is the device
|  &  ;  <  >  (  )  $  `  \  "  '  <space>  <tab>  <newline>
</syntaxhighlight>
</pre>


My testing shows this procedure works (tested by running '''md5sum''' after eject/plug-in) when I need to copy a 9GB file.
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.


==== Reliable way: Split the large file and copy smaller chunks ====
== Check non-English characters ==
<syntaxhighlight lang='bash'>
[https://www.baeldung.com/linux/find-non-ascii-chars How to Find Non-ASCII Characters in Text Files in Linux]
# Use 'sudo iotop -o' to monitor the I/O
<pre>
split -b 4G inputFile  # create xaa, xab, ... files
perl -ne 'print if /[^[:ascii:]]/' sample.txt
cat x* > outputFile    # merge them. md5sum check succeeds
</pre>


type  x* > outputFile  # Windows OS. http://stackoverflow.com/questions/60244/is-there-replacement-for-cat-on-windows
== ls | more without lose color ==
</syntaxhighlight>
{{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.
$ 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.


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).
== ls directories color ==
* split in the internal hdd: 1min 38sec
[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.
* merge in the internal hdd: 37sec
<pre>
* merge in the USB 3.0 drive: 2min 17sec
# 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>


Remember: Use a reliable USB drives.
== ls output with color background ==
[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].


==== The operation could not be completed because the volume is dirty ====
In my case, after I apply '''chmod 755 -R XXXX''', the weird green background color goes away.
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).
== ls output without user/group columns ==
# Open a Windows File Manager
https://unix.stackexchange.com/a/205165
# Right click the USB drive
<pre>
# Properties
ls -lhog
# Tools -> Check now... Start
</pre>
To further skip the first 2 columns (the permissions and link count) we can use
<pre>
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>


Done. Now I can use the drive again.
== 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}'


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.
ls -lhS  . | awk '{print $5 "\t" $9}'
<syntaxhighlight lang='bash'>
umount /dev/sdb1        # thumb drive
sudo fsck /dev/sdb1


sudo fsck -a /dev/sdb1 # auto repair
# Mac
</syntaxhighlight>
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>


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
== ls suddenly wrapping items with spaces in single quotes ==
<pre>
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?]
$ 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***
Better to add '''export QUOTING_STYLE=literal ''' to .bashrc
cause ***SEVERE*** filesystem damage.


Do you really want to continue<n>? no
== ls on BSD/macOS ==
Use the '''-G''' option to get a color output
{{Pre}}
$ ls -G
</pre>
</pre>


=== Multiple files, new directory ===
== realpath ==
* [http://www.howtogeek.com/276516/how-to-remove-multiple-subdirectories-with-one-linux-command/ How to Remove Multiple Subdirectories with One Linux Command]
'''realpath FILENAME''' to get the full path of a file.
<pre>
 
rm -r ~/Documents/htg/{done,ideas,notes}
= tree command =
</pre>
'''tree -d''': show directories only
* [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]
 
<pre>
= cp command =
mkdircd MyNewDirectory
[https://www.howtoforge.com/linux-cp-command/ Linux cp command tutorial for beginners (8 examples)]
 
== copy a directory ==
{{Pre}}
cp -avr Dir1 Dir2
</pre>
</pre>
where -a will preserve the attributes of files/directories, -v means verbally and -r means copy the directory recursively.


=== alias ===
= Copy a file with progress bar with '''pv''' (plus how to eject the USB drive) =
https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/
http://www.tecmint.com/monitor-copy-backup-tar-progress-in-linux-using-pv-command/


<syntaxhighlight lang='bash'>
{{Pre}}
$ alias # list all aliases
sudo apt-get install pv
$ alias | grep ls
pv file1 > file2    # don't forget the ">" operator and the destination is a file, not a directory
$ unalias ls
</pre>
$ 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
</syntaxhighlight>


To avoid using the alias, use one of the following ways (eg use the command's full path)
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.
<syntaxhighlight lang='bash'>
{{Pre}}
$ \ls
sudo apt-get install udisks
$ /bin/ls
$ command ls
$ 'ls'
</syntaxhighlight>


=== lolcat - bring color to text ===
sudo udisks --unmount /dev/sdb1  # /dev/sdb1 is the partition
<syntaxhighlight lang='bash'>
sudo udisks --detach /dev/sdb    # /dev/sdb is the device
sudo apt-get install ruby
</pre>
sudo gem install lolcat
lolcat -h
lolcat --version
fortune | lolcat


ps | lolcat
My testing shows this procedure works (tested by running '''md5sum''' after eject/plug-in) when I need to copy a 9GB file.
man ls | lolcat


lolcat test.R
== Reliable way: Split the large file and copy smaller chunks ==
{{Pre}}
# 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


sudo apt install figlet
type  x* > outputFile  # Windows OS. # https://stackoverflow.com/a/60254
figlet Merry Christmas | lolcat


alias lolls="ls -l | lolcat"
# Use Prefix, and use numeric suffixes starting from 0
lolls
split -b 4M -d inputFile inputFile.part
</syntaxhighlight>
md5sum inputFile
cat inputFile.part* > inputFile2
ech "LONG_MD5_SUM_From_inputFile inputFile2" | md5sum -c
</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.


=== ls ===
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).
==== Follow the symbolic link ====
* split in the internal hdd: 1min 38sec
Use '''-H''' option
* merge in the internal hdd: 37sec
<syntaxhighlight lang='bash'>
* merge in the USB 3.0 drive: 2min 17sec
ls -lH myDir
</syntaxhighlight>


==== ls | more without lose color ====
Remember: Use a reliable USB drives.
<syntaxhighlight lang='bash'>
$ ls --color=auto
$ ls --color | more
</syntaxhighlight>
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 ====
== The operation could not be completed because the volume is dirty ==
[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].
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).


In my case, after I apply '''chmod 755 -R XXXX''', the weird green background color goes away.
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


==== ls on BSD/macOS ====
Done. Now I can use the drive again.
Use the '''-G''' option to get a color output
<syntaxhighlight lang='bash'>
$ ls -G
</syntaxhighlight>


=== File manager ===
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.
==== Cloud commander ====
{{Pre}}
* https://cloudcmd.io/
umount /dev/sdb1        # thumb drive
* 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.
sudo fsck /dev/sdb1


=== [http://meldmerge.org/ Meld] and [http://diffuse.sourceforge.net/about.html Diffuse] ===
sudo fsck -a /dev/sdb1  # auto repair
</pre>


To make meld to be in the right click menu, follow
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
* http://askubuntu.com/questions/112164/how-can-i-diff-two-files-with-nautilus
<pre>
* http://superuser.com/questions/307927/right-click-files-to-meld
$ fsck /dev/sdb1
fsck from util-linux 2.20.1
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdb1 is mounted.


Another method of comparing two files without using the 'browse' button will be to use the command line.
WARNING!!!  The filesystem is mounted.  If you continue you ***WILL***
cause ***SEVERE*** filesystem damage.
 
Do you really want to continue<n>? no
</pre>


The 'nautilus-compare' program does not work from my testing on Ubuntu 14.04.
= Files =
== List files by sorting according to the file size ==
Use the '''-S''' option in ls.


==== Refresh does not work ====
== List files using wildcard without showing files under subdirectories ==
On Ubuntu 14, Meld version is 1.8.4. The current version is 1.16.2 (Jul 30 2016). The current version requires GTK+ 3.14 or higher.
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
<syntaxhighlight lang='bash'>
{{Pre}}
brb@brb-P45T-A:$ ~/binary/meld-3.16.2/bin/meld
$ ls -d R*
Meld requires GTK+ 3.14 or higher.
drwxr-xr-x 15 brb brb     4096 Mar 14 09:48 R-3.4.4
</syntaxhighlight>
-rw-rw-r--  1 brb brb 30474612 Mar 15  2018 R-3.4.4.tar.gz
* http://unix.stackexchange.com/questions/149377/how-to-install-meld-3-11-in-ubuntu-14-04
drwxr-xr-x 15 brb brb    4096 Mar 14 09:31 R-3.5.3
* http://askubuntu.com/questions/638443/how-to-upgrade-gtk-3-10-to-gtk-3-14-on-ubuntu-14-04
-rw-rw-r-- 1 brb brb 30205979 Mar 11 04:04 R-3.5.3.tar.gz
</pre>


==== Final though ====
== Delete multiple files ==
* I install kdiff3 (<2 MB to download) and the 'File' -> 'Reload' (F5) function there works though it shows an extra space on the place I modified.
[http://www.howtogeek.com/276516/how-to-remove-multiple-subdirectories-with-one-linux-command/ How to Remove Multiple Subdirectories with One Linux Command]
* [http://www.scootersoftware.com/download.php Beyond Compare] (commercial $60, trial version can be downloaded)
{{Pre}}
* '''[http://diffuse.sourceforge.net/download.html diffuse]'''. When I modified a file, diffuse can detect a change and ask me to reload the file. I am using the apt-get to install the software and the version number is 0.4.7 (2014). To copy lines from left panel to right panel, use 'Ctrl + Shift + >' or the '''Copy Selection Right''' icon. One drawback is it cannot save the history from the GUI though we can use the command line to include the file names in the arguments.
rm -r ~/Documents/htg/{done,ideas,notes}
* Alternatively we can use WinMerge on Linux. To do that, [https://wiki.winehq.org/Ubuntu install Wine] on Ubuntu. [http://winmerge.org/?lang=en Download Winmerge] (I am using 2.14.0). Then on a terminal, run the following command. At the end, WinMerge will be launched. WinMerge can also be launched from Mint Menu -> Wine -> WinMerge. One problem is I cannot increase the font size (though acceptable) from View -> Select Font.
</pre>
<syntaxhighlight lang='bash'>
wine WinMerge-2.14.0-Setup.exe
</syntaxhighlight>


=== diff ===
== Delete a certain type of files recursively under a directory ==
==== Run diff with large files ====
For example to delete *.o files under the current directory,
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.
{{Pre}}
find . -type f -name '*.o' -delete
</pre>


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.
== Remove all files/directories except for one file/some file type ==
https://unix.stackexchange.com/a/153863
<pre>
# recursively, including hidden ones
find . ! -name 'file.txt' -type f -exec rm -f {} +


==== Directory ====
# Non-recursively
<syntaxhighlight lang='bash'>
find . -maxdepth 1 ! -name 'file.txt' -type f -exec rm -f {} +
diff -qr dir1 dir2
</pre>
</syntaxhighlight>
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.
where '''-q''' means to report only when files differ and '''-r''' is to recursively compare any subdirectories found.


==== diff & colordiff-color in terminal ====
== Remove all hidden files/directories ==
PS. For a GUI version of diff, [http://meldmerge.org/ Meld] works fine.
[https://www.cyberciti.biz/faq/bash-linux-unix-delete-hidden-files-directories-command/ Bash Find And Delete All Hidden Files Directories]
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
rm -rf .??*  # tested, http://labtestproject.com/linuxcmd/rm.html
diff -y file1 file2 | colordiff
 
# Ignore same rows (two ways):
# list all hidden files/directories
# diff -C0 file1 file2 | colordiff
find . -name ".*" -print
# diff -U0 file1 file2 | colordiff
 
# delete all hidden files
find . -name ".*" -type f -delete


# On systems that I have no root right, I need to install it from the source (just need to run the 'make')
find . -name ".DS_Store" -delete
$ diff file1 file2 | ~/bin/colordiff-1.0.18/colordiff.pl
</pre>
</pre>
where -y option means to show the output in two columns.


[[File:Colordiff.png|150px]]
== Create a new directory and cd to it ==
[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]


Interpretation of the '''diff''' output:
== 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 [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].


The first line of the '''diff''' output will contain:
== chown and chmod recursively (-R) ==
* line numbers corresponding to the first file,
Use '''-R''' (capital R).
* a letter ('''a''' for add, '''c''' for change, or '''d''' for delete), and
<pre>
* line numbers corresponding to the second file.
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.


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:
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.


* Lines preceded by a < are lines from the first file;
== Get the chmod numerical value for a file/directory ==
* lines preceded by > are lines from the second file.
https://unix.stackexchange.com/a/46921
* The three dashes ("---") merely separate the lines of file 1 and file 2.
<pre>
<pre>
2,4c2,4
# BSD/OS X:
< I need to run the laundry.
stat -f "%OLp" <file>
< I need to wash the dog.
 
< I need to get the car detailed.
# Linux:
---
stat --format '%a' <file>
> I need to do the laundry.
stat -c %a <file>
> I need to wash the car.
> I need to get the dog detailed.
</pre>
</pre>
After that we can use '''ls -lhog''' to verify.


<syntaxhighlight lang='bash'>
== Files under a directory have question mark attribute  ==
colordiff -ur path1 path2
Use '''sudo chmod -R a+x /some/directory''' to fix. This happened when I unzip a zip file compressed in a Windows OS.
# If you change -ur to -urN then that will also show the contents of files that are only present in one of the paths.
</syntaxhighlight>
[[File:Colordiff2.png|150px]]


The meaning of colors can be found in '''/etc/colordiffrc''' (''man colordiff'')
== Files have an integer owner in attributes ==
* plain=off
[https://unix.stackexchange.com/a/13110 What does the “number” in the owner field of files signify in linux?]
* newtext=darkgreen
* oldtext=darkred
* diffstuff=darkcyan
* cvsstuff=cyan


=== gnome-terminal ===
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.


==== Remember the session ====
You can change the ower and group to an existing owner and group with the commands chown and chgrp respectively.
* [http://manpages.ubuntu.com/manpages/xenial/man1/gnome-terminal.1.html gnome-terminal --help-all] '''--tab-with-profile'''
** https://stackoverflow.com/questions/17422810/opening-terminal-with-multiple-tabs-using-shell-script
** https://stackoverflow.com/questions/1700995/start-gnome-terminal-with-multiple-virtualenv-tabs-and-services-pre-titled
* [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)]
* [https://askubuntu.com/questions/277543/opening-multiple-tabs-with-gnome-terminal Opening multiple tabs with gnome-terminal]: use '''--tab''' and profile options
* [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.
* [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.


The following is proved working on Ubuntu 18.04
== Uppercase S in permissions of a folder and setGID ==
<pre>
* [https://www.linux.com/learn/understanding-linux-file-permissions Understanding Linux File Permissions]
gnome-terminal --tab --working-directory=$HOME/Downloads --tab --working-directory=$HOME/Documents
* [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]
</pre>
* [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?]


==== Fun: piano ====
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'''.
[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 ===
== immutable files ==
==== [https://gnometerminator.blogspot.com/p/introduction.html Terminator] ====
[https://www.linuxtechi.com/file-directory-attributes-in-linux-using-chattr-lsattr-command/ Manage file and directory attributes using chattr and lsattr command]
* [https://www.tecmint.com/linux-terminal-emulators/ 20 Useful Terminal Emulators for Linux]
* https://wiki.archlinux.org/index.php/Terminator (include some keyboard shortcuts)
** Ctrl + Shift+ O Split terminals horizontally
** Ctrl + Shift+ E Split terminals vertically
** mouse can be used to resize split screens and switch to each screen
* [https://askubuntu.com/questions/283830/how-to-change-the-font-of-various-terminal-emulators Change the font size]
* [https://dmaricic.wordpress.com/2011/01/28/terminator-keyboard-shortcuts/ Keyboard shortcuts]
** Shift + Ctrl + p/n: switch to the previous/next view
** Ctrl -: decrease font
** Shift Ctrl +: increase font
* You can take a screenshot to record the directories for all split screens.


==== GNU screen ====
== Display files sorted by modified date in a directory recursively ==
* https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/
* [http://stackoverflow.com/questions/5566310/how-to-recursively-find-and-list-the-latest-modified-files-in-a-directory-with-s stackoverflow.com]
* http://unix.stackexchange.com/questions/7453/how-to-split-the-terminal-into-more-than-one-view
{{Pre}}
stat --printf="%y %n\n" $(ls -tr $(find DIRNAME -type f))
</pre>
* [http://superuser.com/questions/416308/list-files-recursively-and-sort-by-modification-time superuser.com]
{{Pre}}
find -type f -printf '%T+\t%p\n' | sort -n
</pre>
Both of methods give the same output. Note the latest changed file is shown at the bottom of the output.


How to do it...
== Sort files by their size ==
* 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.
use the '-S' option.
* 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.
{{Pre}}
* View a list of open windows: Ctrl + a, then ".
ls -lS
* Switch between windows: Ctrl + a and n for the next window and Ctrl +a and p for the previous window.
</pre>
* 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.


==== tmux* ====
== Files starting with a dash (meta-characters) ==
* https://github.com/tmux/tmux/wiki
[https://www.cyberciti.biz/faq/linuxunix-move-file-starting-with-a-dash/ Move File Starting With A Dash]
* tmux is available in biowulf/helix
{{Pre}}
* [https://www.2daygeek.com/tmux-a-powerful-terminal-multiplexer-emulator-for-linux/ tmux – A Powerful Terminal Multiplexer For Heavy Command-Line Linux User]
$ > '-foo.txt'
* [https://unix.stackexchange.com/questions/549/tmux-vs-gnu-screen tmux vs. GNU Screen]
$ rm "-foo.txt"
* [https://superuser.com/questions/423310/byobu-vs-gnu-screen-vs-tmux-usefulness-and-transferability-of-skills/423390 Byobu vs. GNU Screen vs. tmux — usefulness and transferability of skills]
rm: invalid option -- 'o'
* [https://jozefhajnala.gitlab.io/r/r905-rstudio-terminal/ 4 ways to be more productive, using RStudio's terminal]
Try 'rm ./-foo.txt' to remove the file '-foo.txt'.
* If byobu is installed, then tmux command will start byobu (a modified tmux).
Try 'rm --help' for more information.
* Byobu changed the text color of '''ls''' output while tmux does not (Ubuntu 18.04).
$ rm -- -foo.txt
* [https://github.com/tmux/tmux/wiki/FAQ Change the default prefix] key ("ctrl+b"). Note after a change on '''~/.tmux.conf''', we need to
</pre>
** run 'tmux source-file ~/tmux.conf'
** exit the session and enter again for the change to take effect.  
* For the prefix key, '''ctrl+a''' is easier than "ctrl+b" to type. '''F1...F4''' works too but F1 will have a conflict with Gnome Terminal. I pick '''F4''' for my own convenience.


Features:
== Inodes ==
* Split screens
* https://en.wikipedia.org/wiki/Inode
* Don't worry about connection broken (if used remotely) or computer shutdown unexpectedly (it used locally)
* [https://www.stackscale.com/blog/inodes-linux/ Inodes in Linux: limit, usage and helpful commands]
* Remember the session including split screens even computer shutdown for any reason. Useful for running a long job (wget, rsync, et al).
* [https://linuxhandbook.com/inode-linux/ Everything You Need to Know About inodes in Linux]


Most important keyboard shortcuts:
== Recover Deleted Files ==
{| class="wikitable"
[https://www.makeuseof.com/tag/recover-deleted-files-from-your-linux-system/ How to Recover Deleted Files on Linux]
! Keyboard
! Action
|-
| (ctrl+b), "
| split the pane horizontally
|-
| (ctrl+b), up/down arrow key
| move around panes
|-
| (ctrl+b), d
| detach
|-
| $ tmux ls
| list sessions
|-
| $ tmux attach -t 0
| re-attach session 0
|-
| (ctrl+b), :
resize-pane -U 10


resize-pane -D 10
= alias =
| resize pane
https://www.cyberciti.biz/faq/how-to-turn-on-or-off-colors-in-bash/
increase pane height by 10


decrease pane height by 10
{{Pre}}
|-
$ alias # list all aliases
| (ctrl+b), [
$ alias | grep ls
'q' to quit
$ unalias ls
| [https://superuser.com/questions/209437/how-do-i-scroll-in-tmux scrollback] (Enter copy model)
$ 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
| (ctrl+b), [
$ alias open='xdg-open'
Space
$ alias sshnocheck='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias scpnocheck='scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
$ alias sshserver='ssh user@a-long-domain-name.com'
$ 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.


Enter
To avoid using the alias, use one of the following ways (eg use the command's full path)
 
{{Pre}}
(ctrl+b), ]
$ \ls
 
$ /bin/ls
$ tmux save-buffer foo.txt
$ command ls
| [https://awhan.wordpress.com/2010/06/20/copy-paste-in-tmux/ copy mode] in vi style keybindings
$ 'ls'
select the top of the text
</pre>


select the Bottom of the text and copy
Useful aliases (Added to ~/.bashrc)
 
<pre>
Paste (works in tmux window only. To get the tmux buffer in system clipboard, see [http://www.rushiagr.com/blog/2016/06/16/everything-you-need-to-know-about-tmux-copy-pasting/ here])
alias nano="nano -c --softwrap"
</pre>


Save the buffer to a file
We can use the [https://stackoverflow.com/a/20111180 backslash to escape the double quote (or others like dollar sign)].
|}


My ~/.tmux.conf file
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>
set -g prefix F4                  # change prefix
alias lsof2="sudo lsof -i -P | egrep \"PID|LISTEN\""
unbind C-b
bind F4 send-prefix
set -g mouse on                  # use mouse to scroll
set-window-option -g mode-keys vi # for copy-paste
</pre>
</pre>


==== [http://byobu.co/ Byobu] ====
Use '''unalias [alias name]''' to remove an alias.
Byobu is a GPLv3 open source text-based window manager and [https://en.wikipedia.org/wiki/Terminal_multiplexer terminal multiplexer]. It appeared at [http://dirk.eddelbuettel.com/blog/2018/01/26/#prrd_0.0.2 Think inside the box].
 
== Find file defining an alias ==
[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].


Resources:
= lolcat - bring color to text =
* [https://www.digitalocean.com/community/tutorials/how-to-install-and-use-byobu-for-terminal-management-on-ubuntu-16-04 How To Install and Use Byobu for Terminal Management on Ubuntu 16.04]
{{Pre}}
* https://help.ubuntu.com/community/Byobu
sudo apt-get install ruby
* Cheat sheet: [https://www.cheatography.com/mikemikk/cheat-sheets/byobu-keybindings/pdf/ PDF], [https://openclipart.org/image/2400px/svg_to_png/250251/Byobu-Keybindings.png Png] format
sudo gem install lolcat
lolcat -h
lolcat --version
fortune | lolcat


Most important keyboard shortcuts:
ps | lolcat
{| class="wikitable"
man ls | lolcat
! Keyboard
! Action
|-
| Shift + F2
| split the pane horizontally
|-
| Shift + up/down arrow key
| move around panes
|-
| Shift + Alt + up/down key
| resize panes
|-
| F6
| detach
|}


Summary:
lolcat test.R
* Mouse is useless
* When used with iTerm on Mac, some keys may have a different behaviors.
* If we want to use the 'byobu' command remotely, we first run a ssh connection to a remote computer. Then we type 'byobu' to start a new '''session'''. After some operations, we can type 'exit' to quit the session or use "F6" to detach the session and return to a normal ssh connection.
* Kill a frozen session by '''byobu kill-session -t 1''' where "1" is the session number obtained by '''byobu list-session'''
* Cf '''Session''' (a complete new terminal), '''Windows''' (count from 0, see the status bar), '''Split''' (also called ''pane'')
* Some all keyboard shotcuts rely on the Fx keys. It is not easy or may fail to do that on Mac (needs to hold the 'fn' key) keyboard on a ssh connection.
* F1 to go to help, e.g. key bindings. ESC to go back.
** Shift-F1 will open a new '''window''' (check the status bar for a new number). 'q' to quit the Help Window.
** Use Alt + Left/Right to move focus among windows
* F2 - create a new window. F3/F4 (or Alt-Left/Alt-Right) - move to previous/next '''window'''
** Ctrl-Shift-F2 - create a new '''session''' (not work on Mac keyboard?)
** Alt-Up/Down to move between sessions
* Split screen
** Horizontal (up and down): Shift + F2.
** Vertical: Ctrl + F2.
** Again you cannot use mouse to move the focus:(
** Shift + Left/Right/Up/Down to move focus among splits
** 'exit' to close a split
** Shift-F6 to kill a split
** Shift + Alt + arrow keys: resize split screen
* F5 reload profile, refresh status
** Shift-F5 to toggle some presets in the status lines
** F9 - change configuration (will run 'exit' on macOS)
** [https://unix.stackexchange.com/questions/25209/is-there-a-legend-some-place-that-describes-all-of-these-color-coded-values-at-t Legend of color-coded values at the bottom of byobu]
** https://linux.die.net/man/1/byobu. Yellow background is load average. Light purple ''background'' is related to disk (no work on mac).
** http://manpages.ubuntu.com/manpages/cosmic/en/man1/tmux.1.html#options
** '''$HOME/.byobu/status''' file most related to status
* F6 Detach session and then log out (type 'byobu' to connect again). That is, even you closed a byobu window, it is still in the background. We can test it by using 'htop' or 'ping' commands.
** Type '' 'ps -ef | grep byobu' '' in the ssh connection to find out detached byobu sessions
* F7 Enter scrollback mode
** Move the cursor to the start of the text you want to copy, hit "Space"
** Move the cursor to the end of the text you want to copy and hit "Enter"
** To paste text, open a text editor and hit Alt + Insert or ctrl-a-]. The first time to use ctrl-a, we need to choose either Screen or Emacs mode (I choose Screen). Use '''byobu-ctrl-a''' to reconfigure change this selection. See [https://help.ubuntu.com/community/Byobu Ubuntu] page.
** Alt-PageUp/PageDown - enter and move through scrollback (fn+Alt+Up/Down on Mac keyboard)
* F8 Rename the current window
** Shift-F8 Rename the current session (not work on Mac keyboard)
* F11
** Shift-F11 Zoom in/out a split
** Alt-F11  Break a split to a full window
* F12
** Shift-F12 Toggle on/off Byobu's keybindings (say, Byobu's keybindings conflict with some other program)
** Alt-F12 Toggle on/off Byobu's mouse support (move around splits and resize split size). It becomes more complex when we want to select text.


: [[File:Byobu.png|200px]]
sudo apt install figlet
figlet Merry Christmas | lolcat


=== [https://github.com/Guake/guake Guake] / Yakuake / Tilda ===
alias lolls="ls -l | lolcat"
Drop down terminals for the GNOME / KDE / GTK Environments. Great for quick access to a terminal!
lolls
</pre>


=== System date/time, ntpd ===
= File manager =
* [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]
== Cloud commander ==
* [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://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.


=== Change the date/timestamp of a file - touch ===
= diff =
Modify the file relative to its existing modification time
== Run diff with large files ==
<syntaxhighlight lang='bash'>
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].
filename=MyFileName
 
touch -d "$(date -R -r $filename) - 2 hours" $filename # 2 hours before
Another strategy is to split a large file into small pieces. For example,
touch -d "$(date -R -r $filename) + 2 hours" $filename # 2 hours later
<pre>
</syntaxhighlight>
split -b 500MB FILEname # into 500MB files each
split -l 200 FILEname  # into smaller files with 200 lines each
</pre>


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?]
'''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.


=== Find binary file location ===
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.
* '''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].
<syntaxhighlight lang='bash'>
$ which ls
/bin/ls
</syntaxhighlight>
* '''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]. 
<syntaxhighlight lang='bash'>
$ whereis ls
ls: /bin/ls /usr/share/man/man1p/ls.1p.gz /usr/share/man/man1/ls.1.gz
</syntaxhighlight>
* '''type -a'''
<syntaxhighlight lang='bash'>
$ type -a ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
</syntaxhighlight>


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.
== Kompare ==
For example, the following command will search .png files over the system (not only the personal directory).
https://apps.kde.org/en/kompare
<syntaxhighlight lang='bash'>
locate "*.png"
</syntaxhighlight>


=== find: Find a file ===
Meld cannot change theme. So if my desktop has a dark theme, meld is hard to read.
==== -iname ====
Search by a file name
<syntaxhighlight lang='bash'>
$ find . -iname '*.txt'  # -iname or -name is necessary
</syntaxhighlight>


It also works for searching files on subdirectories.
Kompare still has a light them.
<syntaxhighlight lang='bash'>
$ 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
</syntaxhighlight>


==== -mtime, -ctime, -atime argument ====
== Directory ==
Find files modified in 10 days.
{{Pre}}
<syntaxhighlight lang='bash'>
diff -qr dir1 dir2
$ find . -ctime -10 # include subdirectories
</pre>
.
where '''-q''' means to report only when files differ and '''-r''' is to recursively compare any subdirectories found.
./mediawiki-1.32.0.tar.gz
./d
./d/deepSurv.pdf
</syntaxhighlight>


Find files modified in one day and contain string 'est'
== diff & colordiff-color on terminal: compare side by side ==
<syntaxhighlight lang='bash'>
PS. For a GUI version of diff, [http://meldmerge.org/ Meld] works fine.
$ find . -mtime -1 -exec grep --with-filename est {} \;
Need to install first. apt-get install colordiff. http://www.cyberciti.biz/programming/color-terminal-highlighter-for-diff-files/
</syntaxhighlight>
<pre>
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


If the search directory is not the current directory, we need to add a forward slash to the directory name.
# On systems that I have no root right, I need to install it from the source
<syntaxhighlight lang='bash'>
# (just need to run 'make')
$ find ~/Desktop -iname '*.txt'  # Not working
$ diff file1 file2 | ~/bin/colordiff-1.0.18/colordiff.pl
$ find ~/Desktop/ -iname '*.txt' # Working
</pre>
</syntaxhighlight>
where -y option means to show the output in two columns.


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).
[[File:Colordiff.png|150px]]
<syntaxhighlight lang='bash'>
find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar
</syntaxhighlight>


[https://www.quora.com/What-is-the-difference-between-mtime-atime-and-ctime What is the difference between mtime, atime and ctime?]
Interpretation of the '''diff''' output:
* 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 ====
The first line of the '''diff''' output will contain:
See [[Linux_Programming#xargs|Linux Programming]]
* 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:


==== -exec COMMAND {} + ====
* Lines preceded by a < are lines from the first file (color in red);
Find files and execute something (google: find --exec)
* lines preceded by > are lines from the second file (color in green).
<syntaxhighlight lang='bash'>
* The three dashes ("---") merely separate the lines of file 1 and file 2.
$ find ./ -name "*.tar.gz" -exec tar zxvf {} \;
<pre>
</syntaxhighlight>
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>


* [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].
{{Pre}}
* [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 '{} +'?]
colordiff -ur path1 path2
* [http://unix.stackexchange.com/questions/12902/how-to-run-find-exec How to run find -exec?]
</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]]


The following will find out the total file size of the 'accepted_hits.bam' file under all sub-directories.
The meaning of colors can be found in '''/etc/colordiffrc''' (''man colordiff'' or [https://www.colordiff.org/colordiff.html colordiff web site])
<syntaxhighlight lang='bash'>
* plain=off
find ./ -iname "accepted_hits*" -exec du -ch {} + | grep total$
* newtext=darkgreen
</syntaxhighlight>
* oldtext=darkred
where '-c' produces a grand total, and will substitute {} with the filename(s) found in '''-exec'''.
* diffstuff=darkcyan
* cvsstuff=cyan


==== Application to backup ====
== git diff --no-index -- file.a file.b ==
[[#Delete_files_or_directories_older_than_XXX_days|Delete files/directories older than XXX days]]
[https://stackoverflow.com/a/15110387 Any visual diff in Linux console?]


==== Avoid Permission Denied Messages ====
= gnome-terminal =
[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'''.
<syntaxhighlight lang='bash'>
find . -iname "data*.txt" -print 2>/dev/null
</syntaxhighlight>
* Focus on the 'permission denied' message: '''grep -v "Permission denied" '''
<syntaxhighlight lang='bash'>
find / -name foo 2>&1 | grep -v "Permission denied"
</syntaxhighlight>


=== '''grep''': Find a file by searching contents ===
== Remember the session ==
<syntaxhighlight lang='bash'>
* [http://manpages.ubuntu.com/manpages/xenial/man1/gnome-terminal.1.html gnome-terminal --help-all] '''--tab-with-profile'''
grep -r -i "Entering" ~/Downloads/R-3.0.0/
** https://stackoverflow.com/questions/17422810/opening-terminal-with-multiple-tabs-using-shell-script
</syntaxhighlight>
** https://stackoverflow.com/questions/1700995/start-gnome-terminal-with-multiple-virtualenv-tabs-and-services-pre-titled
where '''-r''' means recursively searching the directory and '''-i''' means case insensitive.
* [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)]
* [https://askubuntu.com/questions/277543/opening-multiple-tabs-with-gnome-terminal Opening multiple tabs with gnome-terminal]: use '''--tab''' and profile options
* [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.
* [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.


Sometimes using '''-R''' is more effective because of the symbolic links issue.
The following is proved working on Ubuntu 18.04
<syntaxhighlight lang='bash'>
<pre>
$ grep -r -i phpmyadmin /etc/apache2/  # nothing returned
gnome-terminal --tab --working-directory=$HOME/Downloads \
$ grep -R -i phpmyadmin /etc/apache2/
              --tab --working-directory=$HOME/Documents
/etc/apache2/conf-enabled/phpmyadmin.conf:# phpMyAdmin default Apache configuration
</pre>
...
/etc/apache2/conf-available/phpmyadmin.conf:# phpMyAdmin default Apache configuration
...
</syntaxhighlight>


We can also display the row numbers for matches by using the '''-n''' parameter in grep.
== Fun: piano ==
<syntaxhighlight lang='bash'>
[https://www.ostechnix.com/let-us-play-piano-terminal-using-pc-keyboard/ Let Us Play Piano In Terminal Using Our PC Keyboard]
# What variants appear in dbsnp
grep -n 'rs[0-9]' XXX.vcf
</syntaxhighlight>


To exclude lines with a pattern, using the '''-v''' parameter.
= Terminals in grids =
<syntaxhighlight lang='bash'>
See [[Terminal_multiplexer|Terminal_multiplexer]].
# How many variant were called
== Tilix ==
grep -v "^#" XXX.vcf | head
</syntaxhighlight>


To show only matched filenames, using the '''-l''' parameter.
== Terminator ==
<syntaxhighlight lang='bash'>
grep -l "iterator" *.cpp
# if we add '-n', the '-n' option won't work.
</syntaxhighlight>


To search with certain file extensions, use '''--include''' argument; see [https://stackoverflow.com/questions/12516937/grep-but-only-certain-file-extensions this post].
== GNU screen ==
<syntaxhighlight lang='bash'>
grep -r -i --include \*.h --include \*.cpp KEYWORD ~/path[12345] 
# escape with \ just in case you have a directory with asterisks in the filenames
</syntaxhighlight>


If the pattern is saved in a file, use the '''-f''' parameter
== tmux* ==
<syntaxhighlight lang='bash'>
grep -f PATTERNFILE INPUTFILE
</syntaxhighlight>


If there are two keywords, use the following
== [http://byobu.co/ Byobu] ==
<syntaxhighlight lang='bash'>
$ 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
</syntaxhighlight>
We can use R to compute the time spent in each step; see [[R#Dealing_with_date|Dealing with dates]].


Check https://www.howtoforge.com/tutorial/linux-grep-command/ for more examples
== [https://github.com/Guake/guake Guake] / Yakuake / Tilda ==
* Using grep to search only for words  ("-w" option)
Drop down terminals for the GNOME / KDE / GTK Environments. Great for quick access to a terminal!
* 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)


==== GUI ====
= System date/time, ntpd =
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
* [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]
<pre>
* [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]
sudo apt-get install searchmonkey
* [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>
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 ====
= Linux file timestamps =
{| class="wikitable"
[https://www.howtogeek.com/517098/linux-file-timestamps-explained-atime-mtime-and-ctime/ Linux File Timestamps Explained: atime, mtime, and ctime]
! Command
 
! Examples
== Change the date/timestamp of a file - touch ==
|-
Modify the file relative to its existing modification time
| find
{{Pre}}
| find [DIRECTORY]  -iname '*.txt'
filename=MyFileName
find [DIRECTORY] -maxdepth 2 -iname *.php
touch -d "$(date -R -r $filename) - 2 hours" $filename # 2 hours before
touch -d "$(date -R -r $filename) + 2 hours" $filename # 2 hours later
</pre>


find -name '*.php' -o -name '*.txt'  # OR operator
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?]
|-
| grep
| grep -r -i "check_samtools" DIRECTORY/
dpkg -l libgtk* | grep  '^i'
|}


=== Count number of columns: awk ===
= Find binary file location, '''type''' =
The following command shows the number of columns for the first few rows of a text file.
* '''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].
<syntaxhighlight lang="bash">
{{Pre}}
head MYFILE | awk '{ print NF}'
$ 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>
* '''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}}
$ type ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
</pre>


head MYFILE | awk -F '\t' '{ print NF}'
* '''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).
</syntaxhighlight>
{{Pre}}
locate "*.png"
</pre>
: 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].


=== Count number of rows in a file: wc ===
= find: Find a file =
<syntaxhighlight lang="bash">
find operates ''recursively'' into sub folders.
wc -l MYFILE
</syntaxhighlight>


The source code of wc (or any Linux command) can be found by using [http://ubuntuforums.org/showthread.php?t=241328 this method]
== -iname ==
<syntaxhighlight lang="bash">
Search by a file name
brb@brb-T3500:~/Downloads$ which wc
{{Pre}}
/usr/bin/wc
$ find . -type f -name "abc*" # find a file starting with abc
brb@brb-T3500:~/Downloads$ dpkg -S /usr/bin/wc
$ find . -iname '*.txt'  # -iname or -name is necessary
coreutils: /usr/bin/wc
</pre>
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>.
It also works for searching files on subdirectories.
 
{{Pre}}
=== Print certain rows/lines of a text file ===
$ find . -name transcripts.gtf
The following example will print out lines 10 to 60 of FILENAME.
./RH_bio/transcripts.gtf
<pre>
./dT_ori/transcripts.gtf
sed -n '10,60p' FILENAME
./dT_tech/transcripts.gtf
./dT_bio/transcripts.gtf
./RH_ori/transcripts.gtf
./RH_tech/transcripts.gtf
</pre>
</pre>
Or to print out line 60,
<pre>
sed -n '60p' FILENAME
</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 ===
== -mtime, -ctime, -atime argument ==
Use [https://raw.githubusercontent.com/pixelb/scripts/master/scripts/ansi2html.sh ansi2html.sh]. It only requires gawk.
Find files modified in 10 days.
# Use wget to download it
{{Pre}}
# sudo apt-get install gawk
$ find . -ctime -10 # include subdirectories
# chmod +x ansi2html.sh
.
# colordiff file1 file2 | ./ansi2html.sh > diff.html
./mediawiki-1.32.0.tar.gz
./d
./d/deepSurv.pdf
</pre>


=== using a the result of a diff in a if statement ===
Find files modified in one day and contain string 'est'
<pre>
{{Pre}}
ls -lR $dir > a
$ find . -mtime -1 -exec grep --with-filename est {} \;
ls -lR $dir > b
</pre>


DIFF=$(diff a b)
<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>
if [ "$DIFF" != "" ]
{{Pre}}
then
$ find ~/Desktop -iname '*.txt'  # Not working
    echo "The directory was modified"
$ find ~/Desktop/ -iname '*.txt' # Working
fi
</pre>
</pre>
Another example
 
<pre>
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).
if [ "$(diff file1.html file2.html)" == "" ]; then echo Same; else echo Different; fi
{{Pre}}
find / -type f -mtime -7 | xargs tar -rf weekly_incremental.tar
gzip weekly_incremental.tar
</pre>
</pre>


=== Prompt ===
[https://www.quora.com/What-is-the-difference-between-mtime-atime-and-ctime What is the difference between mtime, atime and ctime?]
==== Colored prompt ====
* mtime (modification time) indicates the time the contents of the file has been changed. Mind you, only the contents. Not the attributes.
* http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
* 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.
* https://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/
* atime (access time) is the timestamp that indicates the time that a file has been accessed.


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.
== xargs ==
<syntaxhighlight lang='bash'>
See [[Linux_Programming#xargs|Linux Programming]]
# 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
== -exec COMMAND {} + ==
export PS1='\[\e[1;33m\]\u@\h:\w\$ \[\e[0m\]'    # bright yello
* [https://unix.stackexchange.com/a/12904 How to run find -exec?], [https://stackoverflow.com/a/6085237 Using semicolon (;) vs plus (+) with exec in find]
export PS1='\[\e[0;33m\]\u@\h:\w\$ \[\e[0m\]'    # dark yellow (good)
{{Pre}}
find . -exec grep chrome {} \;
# or
find . -exec grep chrome {} +
</pre> find will execute grep and will substitute {} with the filename(s) found. The difference between ; and + is that '''with ; a single grep command for each file is executed''' whereas with + as many files as possible are given as parameters to grep at once. The backslash before ; is to escape ; so linux won't interpret it directly.
* Find files and execute something (google: find --exec)
{{Pre}}
$ find ./ -name "*.tar.gz" -exec tar zxvf {} \;
</pre>
* Find and move files to a new directory
{{Pre}}
find OLDDIR -type f -exec mv -t NEWDIR {} +
</pre>
* [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].
* [https://unix.stackexchange.com/a/196917 What is meaning of {} + in find's -exec command?]
* [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://unix.stackexchange.com/questions/12902/how-to-run-find-exec How to run find -exec?]


# red
The following will find out the total file size of the 'accepted_hits.bam' file under all sub-directories.
export PS1='\[\e[1;31m\]\u@\h:\w\$ \[\e[0m\]'    # bright red
{{Pre}}
export PS1='\[\e[0;31m\]\u@\h:\w\$ \[\e[0m\]'     # dark red (good)
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'''.


# green
== How to find and delete directory recursively ==
export PS1='\[\e[1;32m\]\u@\h:\w\$ \[\e[0m\]'    # bright green
[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.
export PS1='\[\e[0;32m\]\u@\h:\w\$ \[\e[0m\]'    # dark green


# cyan
== Find all soft link files ==
export PS1='\[\e[1;36m\]\u@\h:\w\$ \[\e[0m\]'    # bright cyan
<pre>
export PS1='\[\e[0;36m\]\u@\h:\w\$ \[\e[0m\]'    # dark cyan (good)
find /tmp -type l
</pre>


# purple
== Recursive statistics on file types in directory? ==
export PS1='\[\e[1;35m\]\u@\h:\w\$ \[\e[0m\]'     # bright purple (good)
[https://unix.stackexchange.com/a/18508 You could use '''find''' and '''uniq''' for this]. This is fast!
export PS1='\[\e[0;35m\]\u@\h:\w\$ \[\e[0m\]'    # dark purple
</syntaxhighlight>


[[File:Ps1tweak.png|200px]]
<pre>
$ find . -type f | sed 's/.*\.//' | sort | uniq -c
</pre>


To make a permanent change, we can add the line to '''~/.bashrc''' file and (is it necessary) un-comment the following line
== Exclude or Ignore Files ==
<pre>
[https://www.cyberciti.biz/faq/find-command-exclude-ignore-files/ Find command Exclude or Ignore Files (e.g. Ignore All Hidden .dot Files )]
force_color_prompt=yes
 
== Avoid Permission Denied Messages ==
[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>
</pre>


==== Add a timestamp to your Bash prompt ====
== Find Files That Have Been Modified Recently in Linux ==
* 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'.
[https://www.baeldung.com/linux/recently-changed-files Find Files That Have Been Modified Recently in Linux]
* [http://www.foragoodstrftime.com For a Good Strftime] - Online date/time formatting tool
* http://bneijt.nl/blog/post/add-a-timestamp-to-your-bash-prompt/. Set
{| 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$
|-
| <pre>PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] " </pre> || 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).
== fd: The Find Command Alternative ==
* http://askubuntu.com/questions/193416/adding-timestamps-to-terminal-prompts. Add this line to the '''~/.bashrc''' file:
[https://ostechnix.com/fd-find-command-alternative/ Fd: The Find Command Alternative For Mastering File Search In Linux]
<syntaxhighlight lang='bash'>
export PROMPT_COMMAND="echo -n \[\$(date +%H:%M%p)\]\ "
</syntaxhighlight>
and the output will be something like:
<syntaxhighlight lang='bash'>
[07:03AM] user@hostname:~$
</syntaxhighlight>


==== To the right hand side/Aligned to right and zsh ====
= '''grep''': Find a file by searching contents =
* See an example from [[Ubuntu#BioLinux|Biolinux]]. '''echo $SHELL''' shows Bio-Linux is using zsh.
{{Pre}}
* http://zsh.sourceforge.net/Intro/intro_14.html
grep -r -i "Entering" ~/Downloads/R-3.0.0/
* https://www.howtoforge.com/tutorial/how-to-setup-zsh-and-oh-my-zsh-on-linux/. Note that there is a green arrow for zsh. This is quite special. I need to reboot to see a switch to zsh.
</pre>
* https://superuser.com/questions/362372/how-to-change-the-login-shell-on-mac-os-x-from-bash-to-zsh '''chsh -s /bin/zsh'''
where '''-r''' means recursively searching the directory and '''-i''' means case insensitive.
* https://superuser.com/questions/776759/switch-from-zsh-to-default-os-x. '''chsh -s /bin/bash'''


=== Proxy ===
Sometimes using '''-R''' is more effective because of the symbolic links issue.
[https://www.makeuseof.com/tag/best-web-proxies/ The 15 Best Web Proxies for Geo-Blocked Content and Online Privacy]
{{Pre}}
$ grep -r -i phpmyadmin /etc/apache2/ # nothing returned
$ grep -R -i phpmyadmin /etc/apache2/
</pre>


==== Listen to pandora in Europe: install squid proxy ====
We can also display the row numbers for matches by using the '''-n''' parameter in grep.
http://www.cyberciti.biz/faq/access-pandora-radio-using-proxy-server-outside-usa/
{{Pre}}
# What variants appear in dbsnp
grep -n 'rs[0-9]' XXX.vcf
</pre>


Interestingly, the firefox connection settings should choose '''HTTP Proxy''' instead of 'SOCKS host'.
To exclude lines with a pattern, using the '''-v''' parameter.
{{Pre}}
# How many variant were called
grep -v "^#" XXX.vcf | head
</pre>


=== scp ===
To exclude binary files, use '''-I''' parameter.
==== file path with spaces ====
Use double quotes around the full path and a backslash to escape any space.
<syntaxhighlight lang="bash">
scp [email protected]:"web/tmp/Master\ File\ 18\ 10\ 13.xls" .
</syntaxhighlight>


==== Copy multiple files ====
To show only matched filenames, using the '''-l''' parameter.
<syntaxhighlight lang="bash">
{{Pre}}
scp your_username@domain:~/\{foo.txt,bar.txt\} .
grep -l "iterator" *.cpp
</syntaxhighlight>
# if we add '-n', the '-n' option won't work.
</pre>


Some uses double quotes around the files with the space character to separate files but it does not work when I try to copy files from biowulf to mac.
To search with certain file extensions, use '''--include''' argument; see [https://stackoverflow.com/questions/12516937/grep-but-only-certain-file-extensions this post].
{{Pre}}
grep -r -i --include \*.h --include \*.cpp KEYWORD ~/path[12345] 
# escape with \ just in case you have a directory with asterisks in the filenames
</pre>


==== Recursive copying ====
[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]
Use '''-r''' parameter.
{{Pre}}
grep -Rni --exclude-dir={Private,Personal} --include={*.txt,*.js} 'text' ~/Documents
# Exclude hidden directories
grep -R --exclude-dir=".*" 'text' ~/Documents
</pre>


==== Preserve permissions and modes ====
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.
Use '''-p''' parameter.
<pre>
grep -f searchstringsFile filetosearch > output.txt


==== scp files through one intermediate host ====
# -F, --fixed-strings
http://stackoverflow.com/questions/9139417/how-to-scp-with-a-second-remote-host
grep -F searchstring filetosearch > output.txt
</pre>


The following command is tested.
If the pattern is saved in a file, use the '''-f''' parameter
<syntaxhighlight lang="bash">
{{Pre}}
scp -o 'ProxyCommand ssh user@remote1 nc %h %p' user@remote2:path/to/file .
grep -f PATTERNFILE INPUTFILE
</syntaxhighlight>
</pre>


A second method which is useful for ssh and scp commands
If there are two keywords, use the following
<syntaxhighlight lang="bash">
{{Pre}}
$ ssh -L 9999:host2:22 user1@host1 # leave the terminal
$ grep "begin\|completed" --color swarm_58606147_0.o  # needs an escape
# Open a new terminal
begin 2018-01-12 14:46:05
$ scp -P 9999 fileName user2@localhost:/path/to/dest/fileName  # transfer from local to remote. Note: Upper P.
alignment is completed 2018-01-12 16:45:24
$ scp -P 9999 user2@localhost:/path/to/source/fileName fileName # transfer from remote to local. Note: Upper P.
marking duplication is completed 2018-01-12 17:52:01
# If we only want to use ssh
assign read group is completed 2018-01-12 18:22:49
$ ssh -p 9999 user2@localhost # Note: lower p.
indel re-alignment is completed 2018-01-12 19:29:32
</syntaxhighlight>
BQSR is completed 2018-01-12 22:26:22
 
GATK is completed 2018-01-12 23:43:3
==== scp with non-standard port: -P (capital) ====
$ egrep "begin|completed" --color swarm_58606147_0.o
Use '''-P''' argument.
# no need an escape if we use extended regular expressions
<syntaxhighlight lang='bash'>
</pre>
scp -P 23 myfile user@remoteip:
We can use R to compute the time spent in each step; see [[R#Dealing_with_date|Dealing with dates]].
</syntaxhighlight>
 
==== scp or ssh without password ====
* http://www.thegeekstuff.com/2008/06/perform-ssh-and-scp-without-entering-password-on-openssh/
* https://toic.org/blog/2008/ssh-basics/


Steps:
Check https://www.howtoforge.com/tutorial/linux-grep-command/ for more examples
# Verify that local-host and remote-host is running openSSH ('''ssh -V''')
* Using grep to search only for words / exact match ("-w" option)
# Generate key-pair on the local-host using '''ssh-keygen''' (Enter a passphrase here, do not leave it empty. A passphrase should be at least several words long, something you can easily remember. It's a bad idea to use a single word as a passphrase.)
* Using grep to search two different words  (egrep -w 'word1|word2' /path/to/file)
# Install public key on the remote-host
* Count line for matched words  ("-c" option)
# Give appropriate permission to the .ssh directory on the remote-host ('''chmod 755 ~/.ssh; chmod 644 ~/.ssh/authorized_keys''')
* Grep invert match ("-v" option)
# Login from the local-host to remote-host using the SSH key authentication to verify whether it works properly
* How to list only the names of matching files ("-l" option)
# Start the SSH Agent on local-host to perform ssh and scp without having to enter the passphrase several times ('''ssh-agent $SHELL''')
# Load the private key to the SSH agent on the local-host ('''ssh-add''', need to enter the passphrase 1 time only)
# Perform SSH or SCP to remote-home from local-host without entering the password. It works for all remote machines containing the key from local-local.


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].
== Preserve colouring after piping grep to grep ==
https://stackoverflow.com/a/2327216


==== ssh with password on the command line ====
Use grep '''--color=always''' .For example, grep --color=always KEYWORD Myfile | more.
Install '''sshpass''' utility. See https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password


=== SSH ===
== Compressed files ==
==== Best security practices ====
'''zgrep''' or '''zipgrep''' command
[https://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html Top 20 OpenSSH Server Best Security Practices]
# Use SSH public key based login
# Disable root user login
# Disable password based login
# Limit Users’ ssh access
# Disable Empty Passwords
# Use strong passwords and passphrase for ssh users/keys
# Firewall SSH TCP port # 22
# Change SSH Port and limit IP binding
# Use TCP wrappers (optional)
# Thwart SSH crackers/brute force attacks such as using [https://www.fail2ban.org/wiki/index.php/Main_Page fail2ban] and [https://www.cyberciti.biz/faq/block-ssh-attacks-with-denyhosts/ DenyHosts] software
# Rate-limit incoming traffic at TCP port # 22 (optional)
# Use port knocking (optional)
# Configure idle log out timeout interval
# Enable a warning banner for ssh users
# Disable .rhosts files (verification)
# Disable host-based authentication (verification)
# Patch OpenSSH and operating systems
# Chroot OpenSSH (Lock down users to their home directories)
# Disable OpenSSH server on client computer
# Bonus tips from Mozilla


=== Install OpenSSL ===
== GUI ==
[https://www.howtoforge.com/tutorial/how-to-install-openssl-from-source-on-linux/ How to Install the latest OpenSSL version from Source on Linux]
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
 
==== Way to avoid ssh connection timeout and ~/.ssh/config ====
* https://superuser.com/questions/98562/way-to-avoid-ssh-connection-timeout-freezing-of-gnome-terminal
* https://www.cyberciti.biz/faq/create-ssh-config-file-on-linux-unix/
* [https://linux.die.net/man/5/ssh_config man ssh_config]
 
Put the following in your ~/.ssh/config.
<pre>
<pre>
Host remotehost
sudo apt-get install searchmonkey
  HostName remotehost.com
  Port 4242
  User abcd
  ServerAliveInterval 240
</pre>
</pre>
After that we can run ''ssh remotehost''.  
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.  


To enable it for all hosts use:
== -- option ==
[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]
<pre>
<pre>
Host *
rm --help | grep -w -- -r
  ServerAliveInterval 240
 
rm --help | grep -w -- '-[rf]'  # multiple one letter
</pre>
</pre>
Also make sure to run chmod 600 ~/.ssh/config


==== Change to a different port ====
== Summary of '''find''' and '''grep''' commands ==
<syntaxhighlight lang='bash'>
{| class="wikitable"
$ sudo nano /etc/ssh/sshd_config # looking for the line containing port
! Command
$ sudo service ssh restart # tested on Ubuntu 14.04
! Examples
</syntaxhighlight>
|-
Remember to change the Router settings.
| find
| find [DIRECTORY] -iname '*.txt'
find [DIRECTORY] -maxdepth 2 -iname *.php


On the client PC, use '''ssh USERNAME@HOSTNAME -p NEWPORT''' for a connection.
find -name '*.php' -o -name '*.txt' # OR operator
|-
| grep
| grep -r -i "check_samtools" DIRECTORY/
dpkg -l libgtk* | grep  '^i'
|}


For security reason, use the port < 1024 (privileged ports and can only be opened by root)
= Format the output: column =
* [https://www.adayinthelifeof.nl/2012/03/12/why-putting-ssh-on-another-port-than-22-is-bad-idea/ Why putting SSH on port 2222 is a bad idea]
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].
* [https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers Here] is a list of TCP and UDP port numbers.


==== ssh alias ====
For example: ''mount | column -t''
* [https://www.howtogeek.com/75007/stupid-geek-tricks-use-your-ssh-config-file-to-create-aliases-for-hosts/ Using ssh confi file to create aliases for hosts]
* [http://www.linuxnix.com/5-ssh-alias-examples-using-ssh-config-file/ 5 SSH alias examples in Linux]


With this trick, ssh and scp ('''scp alias_name:Downloads/myfile .''') work perfectly.
* [https://www.geeksforgeeks.org/column-command-in-linux-with-examples/ column command in Linux with examples]
* [https://www.tecmint.com/linux-column-command/ Different Ways to Use Column Command in Linux]
* [https://www.baeldung.com/linux/display-columns-from-file Display Specific Columns From a File in Linux]


Modify '''~/.ssh/config'''
= Count number of columns: awk =
The following command shows the number of columns for the first few rows of a text file.
{{Pre}}
head MYFILE | awk '{ print NF}'


head MYFILE | awk -F '\t'  '{ print NF}'
</pre>
= Count number of rows in a file: wc =
<pre>
<pre>
Host *
wc -l MYFILE
  ServiceAliveInterval 120
</pre>
  ServiceAliveCountMax 30


Host your-alias_name
The source code of wc (or any Linux command) can be found by using [http://ubuntuforums.org/showthread.php?t=241328 this method]
  User username
<pre>
  HostName remote.sshserver.com
brb@brb-T3500:~/Downloads$ which wc
  Port 50001
/usr/bin/wc
  IdentifyFile ~/.ssh/id_file
brb@brb-T3500:~/Downloads$ dpkg -S /usr/bin/wc
  ServiceAliveInterval 120
coreutils: /usr/bin/wc
 
brb@brb-T3500:~/Downloads$ sudo apt-get source coreutils
Host work
  User abcde
  HostName work.workserver.com
  ServiceAliveCountMax 5
  StrictHostKeyChecking yes
</pre>
</pre>


==== Running commands on a remote host ====
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>.
<syntaxhighlight lang='bash'>
ssh user@host 'COMMANDS'


ssh user@host "command1; command2; command3"
= Print certain rows/lines of a text file =
 
The following example will print out lines 10 to 60 of FILENAME.
COMMANDS="command1; command2; command3"
ssh user@host "$COMMANDS"
</syntaxhighlight>
 
A practical example
<syntaxhighlight lang='bash'>
#!/bin/bash
 
IP_LIST="192.168.0.1 192.168.0.5 192.168.0.9"
USER="test"
 
for IP in $IP_LIST;
do
  utime=$(ssh ${USER}@${IP} uptime  | awk '{ print $3 }' )
  echo $IP uptime:  $utime
done
</syntaxhighlight>
 
==== Disable root log in ====
Modify /etc/ssh/sshd_config. Change this line:
<pre>
<pre>
#PermitRootLogin yes
sed -n '10,60p' FILENAME
</pre>
</pre>
to
Or to print out line 60,
<pre>
<pre>
PermitRootLogin no
sed -n '60p' FILENAME
</pre>
</pre>
and run '''/etc/init.d/sshd restart'''.
It seems this method is not as fast as I expected. For example, the '''tail''' command will immediately print out the result without waiting!


However, that line in my Ubuntu is
= Print a text file with line number: less =
[https://www.howtogeek.com/444233/how-to-use-the-less-command-on-linux/ How to Use the less Command on Linux]
<pre>
<pre>
PermitRootLogin without-password
less -N myfile
</pre>
</pre>
According to [https://askubuntu.com/questions/449364/what-does-without-password-mean-in-sshd-config-file this post], “without-password” means password authentication is disabled for root.


==== ssh log files ====
= output colored console to html =
* /var/log/syslog
Use [https://raw.githubusercontent.com/pixelb/scripts/master/scripts/ansi2html.sh ansi2html.sh]. It only requires gawk.
* /var/log/auth.log  (see who is trying to connect; check out http://ip-lookup.net/index.php to see their geolocation)
# Use wget to download it
 
# sudo apt-get install gawk
It is also helpful to check /etc/hosts.allow and /etc/hosts.deny for any possible wrong configuration.
# chmod +x ansi2html.sh
# colordiff file1 file2 | ./ansi2html.sh > diff.html


Note that '''auth.log''' can show ssh security attacks.
= using a the result of a diff in a if statement =
<pre>
<pre>
$ grep sshd /var/log/auth.log
ls -lR $dir > a
Feb 19 11:04:12 phenom sshd[16922]: Failed password for root from 92.62.131.23 port 49383 ssh2
ls -lR $dir > b
Feb 19 11:04:12 phenom sshd[16922]: Received disconnect from 92.62.131.23: 11: Bye Bye [preauth]
Feb 19 11:04:14 phenom sshd[16924]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=92.62.131.23  user=root


Feb 19 11:04:36 phenom sshd[16998]: Invalid user enea from 113.160.227.93
DIFF=$(diff a b)  
Feb 19 11:04:36 phenom sshd[16998]: input_userauth_request: invalid user enea [preauth]
if [ "$DIFF" != "" ]  
Feb 19 11:04:37 phenom sshd[16998]: pam_unix(sshd:auth): check pass; user unknown
then
Feb 19 11:04:37 phenom sshd[16998]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=113.160.227.93
    echo "The directory was modified"
Feb 19 11:04:39 phenom sshd[16998]: Failed password for invalid user enea from 113.160.227.93 port 36090 ssh2
fi
Feb 19 11:04:39 phenom sshd[16998]: Connection closed by 113.160.227.93 [preauth]
</pre>
Feb 19 11:05:11 phenom sshd[17060]: refused connect from 58.218.198.170 (58.218.198.170)
Another example
Feb 19 11:05:55 phenom sshd[17353]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:06:38 phenom sshd[17732]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:07:20 phenom sshd[17850]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:07:40 phenom sshd[17874]: refused connect from 221.194.47.221 (221.194.47.221)
Feb 19 11:08:01 phenom sshd[17955]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:08:41 phenom sshd[18118]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:09:22 phenom sshd[18280]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:10:02 phenom sshd[18353]: Invalid user support from 103.89.89.223
Feb 19 11:10:02 phenom sshd[18353]: input_userauth_request: invalid user support [preauth]
Feb 19 11:10:02 phenom sshd[18353]: pam_unix(sshd:auth): check pass; user unknown
Feb 19 11:10:02 phenom sshd[18353]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=103.89.89.223
Feb 19 11:10:03 phenom sshd[18424]: refused connect from 58.218.198.170 (58.218.198.170)
Feb 19 11:10:04 phenom sshd[18353]: Failed password for invalid user support from 103.89.89.223 port 54218 ssh2
Feb 19 11:10:05 phenom sshd[18353]: fatal: Read from socket failed: Connection reset by peer [preauth]
Feb 19 11:10:07 phenom sshd[18425]: Did not receive identification string from 103.89.89.223
Feb 19 11:10:17 phenom sshd[18443]: Address 113.160.227.93 maps to static.vnpt.vn, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
</pre>
 
==== [http://denyhosts.sourceforge.net/ DenyHosts] ====
Note that [https://askubuntu.com/questions/433924/package-denyhosts-in-ubuntu-trusty-tahr-is-deleted-temporary-or-forever denyhosts package is no longer available in Ubuntu 14.04, 16.04 now]. We can install install from its source DenyHosts-2.6.tar.gz.
 
* [http://idroot.net/linux/install-denyhosts-ubuntu-16-04-lts/ How To Install DenyHosts on Ubuntu 16.04 LTS] and https://www.cyberciti.biz/faq/how-to-install-denyhosts-intrusion-prevention-security-for-ssh-on-ubuntu/
* https://www.digitalocean.com/community/tutorials/how-to-install-denyhosts-on-ubuntu-12-04
* [https://www.tecmint.com/block-ssh-server-attacks-brute-force-attacks-using-denyhosts/ tecmint.com] or [https://www.howtoforge.com/preventing_ssh_dictionary_attacks_with_denyhosts howtoforge] (installed from source)
* '''/etc/hosts.deny''' will records the IPs that are blocked. If the normal ssh connection failed (e.g. get a message ssh_exchange_identification: read: Connection reset by peer), check /etc/hosts.deny file to see if your IP is in it. One method is to add your IP to '''/var/lib/denyhosts/allowed-host''' file so your IP won't be blocked.
* [https://www.enchufa2.es/archives/visualising-ssh-attacks-with-r.html Visualising SSH attacks with R]
* A few minutes of run of denyhosts accumulates hundreds of IP in /etc/hosts.deny file. But I remove the service since I did not spend enough time to understand it.
 
Procedures: follow the README.txt file.
 
==== Log in history: last command ====
The following command also shows how long a user has been logged in.
<pre>
<pre>
last <username> | less
if [ "$(diff file1.html file2.html)" == "" ]; then echo Same; else echo Different; fi
</pre>
</pre>


'''w/who''' can show who (and when) are currently logging in.
= Prompt =
== 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/


==== Generate a strong password ====
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.
Put in your ~/.bashrc. See [https://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html Top 20 OpenSSH Server Best Security Practices].
{{Pre}}
<syntaxhighlight lang='bash'>
# blue 
$ genpasswd() {
export PS1='\[\e[1;34m\]\u@\h:\w\$ \[\e[0m\]'    # bright blue (good)
local l=$1
export PS1='\[\e[0;34m\]\u@\h:\w\$ \[\e[0m\]'    # darker blue
      [ "$l" == "" ] && l=20
      tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
$ genpasswd 16
</syntaxhighlight>


==== login banners/messages ====
# yellow
https://kerneltalks.com/tips-tricks/how-to-configure-login-banners-in-linux/
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)


There are two types of banners you can configure.
# 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)


Banner message to display before user log in (configure in file of your choice eg. /etc/login.warn)
# green
Banner message to display after user successfully logged in (configure in /etc/motd)
export PS1='\[\e[1;32m\]\u@\h:\w\$ \[\e[0m\]'    # bright green
export PS1='\[\e[0;32m\]\u@\h:\w\$ \[\e[0m\]'    # dark green


=== ssh key ===
# cyan
SSH key is useful if you want a password-less login to a remote system. Some useful resources:
export PS1='\[\e[1;36m\]\u@\h:\w\$ \[\e[0m\]'    # bright cyan
* https://help.ubuntu.com/community/SSH/OpenSSH/Keys
export PS1='\[\e[0;36m\]\u@\h:\w\$ \[\e[0m\]'    # dark cyan (good)
* https://help.github.com/articles/generating-ssh-keys


Also there are different kinds of keys (see for example  <~/.ssh/known_hosts file>): [https://en.wikipedia.org/wiki/RSA_(cryptosystem) RSA], [https://en.wikipedia.org/wiki/Digital_Signature_Algorithm DSA] and [https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm ECDSA] (newer). They're keys generated using different encryption algorithms. See [https://security.stackexchange.com/questions/23383/ssh-key-type-rsa-dsa-ecdsa-are-there-easy-answers-for-which-to-choose-when SSH key-type, rsa, dsa, ecdsa, are there easy answers for which to choose when?]
# 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
</pre>


The steps are
[[File:Ps1tweak.png|200px]]
* Check if there is an existing key
 
<syntaxhighlight lang='bash'>
To make a permanent change, we can add the line to '''~/.bashrc''' file and (is it necessary) un-comment the following line
ls -al ~/.ssh
</syntaxhighlight>
* Create a new RSA key pair:
<syntaxhighlight lang='bash'>
ssh-keygen -t rsa
ssh-keygen -f ~/.ssh/personalid -C "bitbucket"
</syntaxhighlight>
where the comment 'bitbucket' will appear at the end of <~/.ssh/personalid> file.
* 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 -i ~/.ssh/id_rsa.pub [email protected] # this will 'append' the key to the remote-host’s .ssh/authorized_key.
</syntaxhighlight>
Or (may not work:()
<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 [email protected]'.
* To disable the password for root login. Type ''sudo nano /etc/ssh/sshd_config''
<pre>
<pre>
PermitRootLogin without-password
force_color_prompt=yes
</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>
</pre>
in sshd_config.


==== Multiple ssh keys ====
<Method 1> If we want to use a specific key in ssh, use
<syntaxhighlight lang='bash'>
ssh -i ~/.ssh/xxx_id_rsa [email protected]
</syntaxhighlight>


<Method 2> Another way is to use '''ssh-add''' & '''ssh-agent''' to manager your keys. ssh-agent keeps your key in its memory and pulls it up whenever it is asked for it.
Some of my settings in .bashrc file
<syntaxhighlight lang='bash'>
<pre>
$ ssh-keygen -f ~/.ssh/personalid -C "bitbucket"
# Office Linux Mint, bright blue, display current time
$ eval $(ssh-agent -s)       # Ensure ssh-agent is enabled:
# Example: 12:45PM ~/Downloads$
$ ssh-add ~/.ssh/personalid  # ssh-add program will ask you for your passphrase
PS1="\[\033[1;34m\]\$(date +%H:%M%p) \w$\[\033[0m\] "
$ ssh-add -l
</syntaxhighlight>


<Method 3> <~/.ssh/config> file.
# Biowulf and Helix, dark yellow
* http://askubuntu.com/questions/269140/how-to-use-multiple-ssh-keys-with-different-accounts-and-hosts or http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/
# Example: biowulf:~/R$
* [https://confluence.atlassian.com/pages/viewpage.action?pageId=271943168 Configure multiple SSH identities for bitbucket accounts]  
PS1='\[\e[0;33m\]\h:\w\$ \[\e[0m\]'
* [https://gist.github.com/jexchan/2351996 Multiple SSH Keys settings for different github account]
alias nano="nano -c --softwrap"


==== ssh key management ====
# Mac, light green
* Using [https://www.howtoforge.com/tutorial/ssh-key-management-with-privacyidea/ privacyIDEA] (howtoforge.com).
export PS1="\[\e[0;32m\]mac$\[\e[0m\] "
</pre>


==== Copy ssh keys to another computer ====
== Shorten prompt ==
http://askubuntu.com/questions/134975/copy-ssh-private-keys-to-another-computer
[https://askubuntu.com/a/145626 How can I shorten my command line (bash) prompt?] It is useful especially in VM.


<syntaxhighlight lang='bash'>
== Add a timestamp to your Bash prompt ==
$ chown brb:brb ~/.ssh/id_rsa*
* 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'.
$ chmod 600 ~/.ssh/id_rsa
* [http://www.foragoodstrftime.com For a Good Strftime] - Online date/time formatting tool
$ chmod 644 ~/.ssh/id_rsa.pub
* http://bneijt.nl/blog/post/add-a-timestamp-to-your-bash-prompt/. Set
</syntaxhighlight>
: {| 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>


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.
== '''zsh''': display time to the right hand side ==
add a line RPROMPT='%*' to ~/.zshrc


==== Preserve ssh keys when upgrading computers ====
= Proxy =
* An article from [http://www.bsdnewsletter.com/bsda-book/Preserve_existing_SSH_host_keys_during_a_system_upgrade.html bsdnewsletter.com].
[https://www.makeuseof.com/tag/best-web-proxies/ The 15 Best Web Proxies for Geo-Blocked Content and Online Privacy]
* https://askubuntu.com/questions/17097/how-to-backup-restore-the-host-key-in-ssh-server
<syntaxhighlight lang='bash'>
ls -l /etc/ssh/*key* > ~/key_list  # optional
mkdir ~/serverkeys && sudo cp -p /etc/ssh/*key* ~/serverkeys/ # back up, -p will preserve mode, ownership and timestamps
sudo cp -p ~/serverkeys/*key* /etc/ssh  # copy back
ls -l /etc/ssh/*key* | diff - ~/key_list # optional
</syntaxhighlight>
If diff produces no output, you're finished.


Pay attention to the permissions. All the /etc/ssh/* files should be owned by root:root, with 644 permissions except for those that end in *key, which should be 600.
== Listen to pandora in Europe: install squid proxy ==
<pre>
http://www.cyberciti.biz/faq/access-pandora-radio-using-proxy-server-outside-usa/
udooer@udoo:~$ ls -l /etc/ssh/*key*
total 32
-rw------- 1 root root  668 Dec  8 14:43 ssh_host_dsa_key
-rw-r--r-- 1 root root  599 Dec  8 14:43 ssh_host_dsa_key.pub
-rw------- 1 root root  227 Dec  8 14:43 ssh_host_ecdsa_key
-rw-r--r-- 1 root root  171 Dec  8 14:43 ssh_host_ecdsa_key.pub
-rw------- 1 root root  399 Dec  8 14:43 ssh_host_ed25519_key
-rw-r--r-- 1 root root  91 Dec  8 14:43 ssh_host_ed25519_key.pub
-rw------- 1 root root 1679 Dec  8 14:43 ssh_host_rsa_key
-rw-r--r-- 1 root root  391 Dec  8 14:43 ssh_host_rsa_key.pub


udooer@udoo:~$ cd /etc/ssh; sudo tar -czvf ~/Downloads/sshkeys.tar.gz *key*
Interestingly, the firefox connection settings should choose '''HTTP Proxy''' instead of 'SOCKS host'.
-rw------- root/root      668 2017-12-08 14:43 ssh_host_dsa_key
-rw-r--r-- root/root      599 2017-12-08 14:43 ssh_host_dsa_key.pub
-rw------- root/root      227 2017-12-08 14:43 ssh_host_ecdsa_key
-rw-r--r-- root/root      171 2017-12-08 14:43 ssh_host_ecdsa_key.pub
-rw------- root/root      399 2017-12-08 14:43 ssh_host_ed25519_key
-rw-r--r-- root/root        91 2017-12-08 14:43 ssh_host_ed25519_key.pub
-rw------- root/root      1679 2017-12-08 14:43 ssh_host_rsa_key
-rw-r--r-- root/root      391 2017-12-08 14:43 ssh_host_rsa_key.pub


udooer@udoo:~/$ cd /etc/ssh; sudo tar -xzvf ~/Downloads/sshkeys.tar.gz 
= SSH, scp =
</pre>
See [[Ssh|ssh]].


==== Disable SSH host key checking ====
= Graphical way to display disk usage =
<syntaxhighlight lang='bash'>
* http://www.makeuseof.com/tag/how-to-analyze-your-disk-usage-pattern-in-linux/
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no [email protected]
For example, to use xdiskusage, we run '''apt-get install xdiskusage''' and launch it by '''xdiskusage ~/'''.
</syntaxhighlight>
* Ubuntu has a built-in program called "Disk Usage Analyzer". Just search it from Dash. Looks useful!
 
= df : Display disk space =
{{Pre}}
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)


To disable the checking for all hosts, in your '''~/.ssh/config''' (if this file doesn't exist, just create it):
df -h | grep -v snap # ignore snap partitions
<pre>
df -h | grep -v loop
Host *
    StrictHostKeyChecking no
</pre>
</pre>


==== Handling the ssh key change when connecting to a remote machine ====
Note for the NTFS type, it will be reported as '''fuseblk''' by mount or df command.
An article from [http://www.cyberciti.biz/faq/warning-remote-host-identification-has-changed-error-and-solution/ cybercitz.biz].


* Method 1. Remove the key using '''ssh-keygen -R''' command.
== duf ==
<syntaxhighlight lang='bash'>
[https://www.omgubuntu.co.uk/2022/06/duf-alternative-to-df-command Terminal Tip ‘duf’ is Prettier Alternative to the ‘df’]
$ ssh-keygen -R {server.name.com}
$ ssh-keygen -R {ssh.server.ip.address}
$ ssh-keygen -R server.example.com
$ ssh-keygen -f "/home/$USERNAME/.ssh/known_hosts" -R "xxx.xxx.x.xx"
</syntaxhighlight>
* Method 2. Add correct host key in /home/user/.ssh/known_hosts
* Method 3. Just delete the known_hosts file If you have only used one ssh server


=== SSH Port forwarding ===
= Disk encryption =
* Chapter 9 Port forward. SSH Mastery OpenSSH, PuTTY, Tunnels and Keys by Michael W. Lucas
[https://guardianproject.info/code/luks/ LUKS]


==== Verizon Quantum Gateway Router ====
== Encrypt files ==
[https://www.verizon.com/cs/groups/public/documents/adacct/fios-qgr-userguide140925.pdf User guide] p98. Click 'Advanced' button first.
[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)]
* Source port: Any (''this is the key'')
* Destination Ports: the port you want to use (connect from outside)
* Forward to Port: Same as incoming port or the port used in the local computer


==== What is tunnel ====
= rm command and trash can =
https://www.howtogeek.com/299845/why-is-a-network-tunnel-called-a-tunnel/. A tunnel provides a ''direct path'' that avoids some type of complexity you would otherwise have to deal with.
[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]


==== Local port forwarding ====
= du/ncdu and block size: Display directory size with sorting and human readable =
* https://toic.org/blog/2010/ssh-port-forwarding/
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.
* https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/
* https://www.ssh.com/ssh/tunneling/example


This port forwarding involves three computers (local, remote/application server, host/secure shell server). If the remote is the same as the host, it will be reduced to involving 2 computers.
'''ncdu''' can show the hidden directory size. This is useful. For example, '''~/.local/share/Trash''' and '''~/.singularity/docker''' can take a lot of space.


For example, we like to access home's router (192.168.1.1) information from an outsider computer. Suppose the host 'hostname' is one computer in the home network and it can be accessed from outside world.
{{Pre}}
sudo apt-get install ncdu
ncdu
</pre>


Another example is if we want to use Jupyter running on a remote machine from  local browser.
* http://www.cyberciti.biz/faq/linux-check-disk-space-command/
<syntaxhighlight lang='bash'>
And the ''du'' method.
# ssh -L localPort:remoteIP:remotePort username@hostname
{{Pre}}
ssh -L 8080:192.168.1.1:80 username@hostname
du -csh *.jpg          # total is at the bottom
ssh -i someKey.pem -L 443:127.0.0.1:8888 username@hostname
du -sh ~/*              # won't include hidden directories, Fast
</syntaxhighlight>
du -h ~/ --max-depth=1  # include hidden directories, SLOW
The -L option specifies local port forwarding. In this case, port 8080 on the local machine was forwarded to port 80 on the remote machine. For the duration of the SSH session, pointing your browser at http://localhost:8080/ would send you to http://192.168.1.1/ as if you are in the same local network of 'hostname'.
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>
The --exclude is to hide hidden directories, '-n' is to compare according to string numerical value, and '-r' is to reverse the result.


The reason it works is because the 'ssh' trick. In addition to being able to make yourself in the home network environment, the traffic on http://localhost:8080 is encrypted too.
Note that the 'du' commands may be cheating. See the following screenshot.


Note that this forwarding uses port 8080 on the client rather than port 80. Binding to port 80 would require using root privileges every time we SSH.
[[File:DiskUsage.png|100px]]


To stop the ssh session, use ps -ef to find the process id and kill it.
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.


==== Remote port forwarding (Reverse port forwarding) ====
{{Pre}}
* https://www.howtoforge.com/reverse-ssh-tunneling (use ssh option '''-f''' to detach ssh process from the tty, '''-N''' to not execute any command over ssh and option '''-i''' for key authentication)
$ sudo dumpe2fs /dev/sda1 | grep -i "block size"
* http://man.openbsd.org/ssh
dumpe2fs 1.41.14 (22-Dec-2010)
* https://toic.org/blog/2009/reverse-ssh-port-forwarding/
Block size:               4096
* https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/


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.
$ sudo tune2fs -l /dev/sda1 | grep -i "block size"


<syntaxhighlight lang='bash'>
$ sudo fdisk -l | tail
ssh -R 8000:localhost:80 user@REMOTE_MACHINE
$ sudo tune2fs -l /dev/mmcblk0p2 | grep -i "block size"
</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.


Example 2: Suppose you have two machine
To show a file size in terms of blocks, we can use
* machine A (userA): under firewall. cannot be directly accessed (like corporate machines)
{{Pre}}
* machine B (userB): local machine (like home machines)
ls -s
Our goal is to access machine A directly from machine B.
</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.


We can run the following on the machine A
== gdu ==
<syntaxhighlight lang='bash'>
[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.)]
# ssh -R remoteIP:remoteport:localIP:localport hostname
# ssh -R remoteport:localIP:localport hostname
ssh -R 2222:localhost:22 userB@machineB_IP
ssh -i /path/to/priv/key/id_rsa -f -N -R 2222:localhost:22 userB@machineB_IP
</syntaxhighlight>
Then we can access machine A from machine B by
<syntaxhighlight lang='bash'>
ssh -p 2222 userA@localhost
</syntaxhighlight>


If you want remote port forwarding configured every time you connect to a host, use the RemoteForward
== Find the total size of certain files within a directory ==
option in ssh_config .
[https://unix.stackexchange.com/a/41552 Find the total size of certain files within a directory branch]
<syntaxhighlight lang='bash'>
<pre>
LocalForward server-IP:server-port client-IP:client-port
du -ch ./photos/*.jpg | grep total
</syntaxhighlight>
find ./photos -type f -name '*.jpg' -exec du -ch {} + | grep total$
</pre>


==== 'D'ynamic port forwarding, SOCKS proxy, bypass blocked websites from work computer ====
= Apache benchmark (ab) testing =
* 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/
* https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/
<pre>
<pre>
ssh -D 4096 user@remoteip
ab -n 100 -c 10 http://taichimd.us/
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.
* http://www.petefreitag.com/item/689.cfm
* http://en.wikipedia.org/wiki/ApacheBench


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 (SOCKS5 by default) Host''' and '4096' for the Port. Don't enter 'localhost' in the HTTP Proxy.
= 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]


Note that in addition to the Firefox, we can use
{{Pre}}
* [[#Chrome_or_Chromium|Chrome or chromium]]
# Method 1: rsync
* [http://sockslist.net/articles/socks-seamonkey-how-to-use SeaMonkey] (seems better than Firefox since the form works better on 1024x600 resolution).
rsync --progress -a sourceDirectory destinationDirectory
* Brave browser does not support proxy
rsync --info=progress2 source dest


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.
# Method 2: pv
sudo apt-get install pv
## copy a single file
pv inputfile > outputfile


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.
## multiple files or directories
tar c sourceDirectory | pv | tar x -C destinationDirectory


==== Backgrounding OpenSSH Forwarding ====
## https://stackoverflow.com/a/26226261
Use the -N flag to tell ssh to not run anything, including a terminal, on the remote server, and the -f flag to tell ssh to go into the background on the client.
docker save <image> | bzip2 | pv | \
<syntaxhighlight lang='bash'>
    ssh user@host 'bunzip2 | docker load'
ssh -fNL 2222:localhost:22 user@remotehost &
</pre>
</syntaxhighlight>
 
By backgrounding this command, you get your original terminal back.
= rsync =
See [[Backup|Backup]].


==== ssh through an intermediate server ====
== Wireless File Transfer Apps on Linux ==
* http://www.cyberciti.biz/faq/linux-unix-ssh-proxycommand-passing-through-one-host-gateway-server/
[https://www.makeuseof.com/wireless-file-transfer-apps-linux/ The 7 Best Wireless File Transfer Apps on Linux]
* https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts#Port_Forwarding_via_an_Intermediate_Host (more examples)


Simple method is
= sudo =
<syntaxhighlight lang="bash">
== How to Control sudo Access on Linux ==
$ ssh -tt vivek@Jumphost ssh -tt vivek@FooServer
https://www.howtogeek.com/447906/how-to-control-sudo-access-on-linux/
</syntaxhighlight>
<pre>
sudo adduser NEWUSER
sudo usermod -a -G sudo NEWUSER
</pre>


Another method is to use ssh ProxyCommand to tunnel connections.
== sudo vs su ==
[https://phoenixnap.com/kb/sudo-vs-su-differences The Difference Between sudo and su Explained]: password and shell.


A third method is to  
== How to Keep ‘sudo’ Password Timeout Session Longer in Linux ==
<syntaxhighlight lang="bash">
http://www.tecmint.com/set-sudo-password-timeout-session-longer-linux/
$ ssh -L 9999:host2:22 user1@host1  # leave this terminal
# open a new terminal tab
$ ssh -p 9999 user2@localhost
</syntaxhighlight>


=== Graphical way to display disk usage ===
== How to run multiple commands in sudo ==
* http://www.makeuseof.com/tag/how-to-analyze-your-disk-usage-pattern-in-linux/
https://www.cyberciti.biz/faq/how-to-run-multiple-commands-in-sudo-under-linux-or-unix/
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!


=== Display files sorted by modified date in a directory recursively ===
== Run sudo commands without a password? ==
* [http://stackoverflow.com/questions/5566310/how-to-recursively-find-and-list-the-latest-modified-files-in-a-directory-with-s stackoverflow.com]  
* [https://www.makeuseof.com/using-sudo-without-password/ How to Use sudo Commands Without Password in Linux]
<syntaxhighlight lang='bash'>
* [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?]
stat --printf="%y %n\n" $(ls -tr $(find DIRNAME -type f))
</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 ===
= Alternative browsers, text browsers =
use the '-S' option.
See [[Browser|Browser]].
<syntaxhighlight lang='bash'>
ls -lS
</syntaxhighlight>


=== df : Display disk space ===
= Filezilla =
<syntaxhighlight lang='bash'>
[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.
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)


df -h | grep -v snap # ignore snap partitions
= The device is busy =
df -h | grep -v loop
* http://oletange.blogspot.com/2012/04/umount-device-is-busy-why.html
</syntaxhighlight>
<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>


Note for the NTFS type, it will be reported as '''fuseblk''' by mount or df command.
* See http://ocaoimh.ie/2008/02/13/how-to-umount-when-the-device-is-busy/
<pre>
# fuser -m /dev/sdc1
/dev/sdc1: 538
# 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>


=== rm command and trash can ===
= mkfs command =
[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]
== 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/


=== du and ncdu : Display directory size with sorting and human readable ===
cd /mnt/geek
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.
cp ~/Documents/Code/*.? .


'''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 umount /mnt/geek
cd /mnt
sudo rmdir geek
</pre>


<syntaxhighlight lang='bash'>
== Format a USB drive: exfat ==
sudo apt-get install ncdu
[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])
ncdu
</syntaxhighlight>


* http://www.cyberciti.biz/faq/linux-check-disk-space-command/
This is a GUI application. After the installation, search "USB Stick Formatter".
And the ''du'' method.
<syntaxhighlight lang='bash'>
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
</syntaxhighlight>
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.
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.


[[File:DiskUsage.png|100px]]
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.
{{Pre}}
sudo apt install exfat-fuse exfat-utils # ubuntu 20.04 and lower
sudo apt install exfat-fuse exfatprogs # ubuntu 22.04 and higher


The discrepancy is explained by 'sector'. See http://askubuntu.com/questions/122091/difference-between-filesize-and-size-on-disk.
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.  


<syntaxhighlight lang='bash'>
sudo mkfs.exfat -n Staples /dev/sdc1
$ sudo dumpe2fs /dev/sda1 | grep -i "block size"
sudo fdisk -l /dev/sdc # still Linux? but Gparted shows exfat
dumpe2fs 1.41.14 (22-Dec-2010)
Block size:              4096
</syntaxhighlight>


To show a file size in terms of blocks, we can use  
sudo mount /dev/sdc1 /mnt # to use
<syntaxhighlight lang='bash'>
</pre>
ls -s
</syntaxhighlight>
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 ===
Note that '''fdisk''' or '''sfdisk''' cannot differentiate NTFS/exFAT. But [https://en.wikipedia.org/wiki/Cfdisk cfdisk] or '''GParted''' can.
<pre>
{{Pre}}
ab -n 100 -c 10 http://taichimd.us/
sudo cfdisk /dev/sdX
</pre>
</pre>
* http://www.petefreitag.com/item/689.cfm
* http://en.wikipedia.org/wiki/ApacheBench


=== Monitor progress of running a command ===
== Create an ext3/ext4 file system on a USB flash drive ==
[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]
* 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.


<syntaxhighlight lang='bash'>
<pre>
# Method 1: rsync
umount /dev/sdb1  (depending on the device of course)
rsync --progress -a sourceDirectory destinationDirectory
lsblk    # check the drive's partition name
rsync --info=progress2 source dest
sudo mkfs -t ext4 /dev/sdb1
lsblk -f  # Verify


# Method 2: pv
sudo mkfs.ext3 /dev/sdb1
sudo apt-get install pv
sudo e2label /dev/sdb1 usbdrive  (change the label)
## copy a single file
pv inputfile > outputfile


## multiple files or directories
sudo mkfs.vfat /dev/sdb1  # MS-DOS
tar c sourceDirectory | pv | tar x -C destinationDirectory
</pre>
</syntaxhighlight>


=== rsync ===
== exFat - cross platform partition format ==
==== Dry run ====
*[[Mac#ExFat:_Best_drive.2Fpartition_format_to_share_data_between_Mac.2C_Linux_and_OS_X|Mac]]
* '''--dry-run''' https://www.tecmint.com/rsync-local-remote-file-synchronization-commands/
* Gparted cannot create exFAT partition (it is greyed out)
* '''-n''' https://linux.die.net/man/1/rsync
* [http://www.makeuseof.com/tag/exfat-better-different-fat32/ This Trick Makes a USB Drive Work Perfectly With Windows, Mac, Linux, and Anything Else]
<syntaxhighlight lang='bash'>
* [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?]
rsync -avn master.bioconductor.org::release
* [https://www.addictivetips.com/ubuntu-linux-tips/format-sd-card-exfat-in-ubuntu/ How to format an SD Card to ExFat in Ubuntu]
</syntaxhighlight>
{{Pre}}
 
sudo apt-get install exfat-utils exfat-fuse
==== Copy large file ====
# Still need to create a partition (ex. FAT32) first using gparted in order to get it mounted
If we need to copy large file (say > 4GB), we shall
sudo fdisk -l
# format USB drive to NTFS (exFat seems not work)
sudo mkfs.exfat -n LABEL /dev/sd**  #  LABEL with whatever you want to label your drive
# Run ''rsync --progress source dest''
# Run ''sync''
 
The last step (rsync) is important. We can use '''sudo iotop''' to check if ''rsync'' is finished or not.
 
==== speed comparison of cp vs rsync ====
[http://withr.me/cp-rm-rsync/ BigData basic: copy & delete folder containing large number of files]
 
==== Incremental backup: '''--link-dest''' ====
<syntaxhighlight lang='bash'>
rsync -aP --link-dest=PATHTO/$PREVIOUSBACKUP $SOURCE $CURRENTBACKUP
</syntaxhighlight>
* [https://blog.interlinked.org/tutorials/rsync_time_machine.html Time Machine for every Unix out there]
* [https://opensource.com/article/18/8/automate-backups-raspberry-pi Automating backups on a Raspberry Pi NAS]


==== rsync with exclude files/directories ====
lsblk -f # verify the partitions, no sudo is needed
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.
<syntaxhighlight lang='bash'>
rsync -avz --exclude '/path1/path2/file' source/ destination/
</syntaxhighlight>
We add add multiple '''--exclude''' to exclude more files/directories.
 
==== rsync to exclude hidden files/directories ====
<syntaxhighlight lang='bash'>
--exclude=".*" # exclude both hidden files and directories
--exclude ".*"  # same as above
 
--exclude ".*/" # exclude hidden directories ONLY
 
--exclude ".DS_Store"
 
--exclude ".git" # exclude .git directory ONLY; relative to the directory to be synchronized.
</syntaxhighlight>
 
==== rsync with -a option ====
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.
 
==== rsync with non-standard port ====
Use '''-e''' option
<pre>
rsync -avz -e "ssh -p 23" mydir user@remoteip:
</pre>
</pre>
This should delivery a working exfat file system (read and write support, but not formatting the drives with exfat via Gnome Disks and GParted).


==== rsync with progress bar ====
= Add a new user with home directory; list all users =
Use '''--progress''' option.
<pre>
<pre>
rsync -avz --progress file1 file2
adduser xxx
</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.
'''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.


==== rsync on Windows ====
To delete the user and home directory, use
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.
 
Below are my note by using cwrsync v3.1.0 installer got from http://www.rsync.net.
<pre>
<pre>
cd C:\Program Files (x86)\cwRsync\bin
deluser --remove-home xxx
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" xxx@taichi.selfip.net:Downloads/
</pre>
</pre>


=== sudo ===
To view the user information, type '' '''id USERNAME''' '' or ''cat /etc/passwd''.
==== 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.howtogeek.com/803907/linux-list-users/ How to List Users in Linux] '''cat /etc/passwd | wc -l'''
https://www.cyberciti.biz/faq/how-to-run-multiple-commands-in-sudo-under-linux-or-unix/


==== How do I run specific sudo commands without a password? ====
= gzip with multi cores: pigz =
https://askubuntu.com/questions/159007/how-do-i-run-specific-sudo-commands-without-a-password
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.


=== Text browser ===
According to 'pigz --help', the default threads is the number of online processors, or 8 if unknown.
==== Links ====
* http://pcworld.com/article/3196428/linux/why-installing-a-text-mode-web-browser-is-a-good-idea.html
* http://links.twibright.com/user_en.html
* https://en.wikipedia.org/wiki/Links_%28web_browser%29


=== Alternative browsers ===
{{Pre}}
==== Chrome or Chromium ====
sudo apt-get install pigz
Install the latest version of chromium.
pigz -9 FILENAME  # best compression method & convert the file to FILENAME.gz
<syntaxhighlight lang='bash'>
sudo apt install curl git
git clone https://github.com/scheib/chromium-latest-linux.git
cd chromium-latest-linux
./update-and-run.sh


# next time
tar cf - paths-to-archive | pigz -9 -p 12 > archive.tar.gz
./run.sh
</pre>
</syntaxhighlight>
There is no need to use '''pigz''' to un-compress the file. '''gunzip''' is fast enough and only takes 4 minutes to decompress.


[https://ubuntuportal.com/2011/12/how-to-change-proxy-settings-chromium-browser-on-ubuntu-11-10.html To use a proxy server],
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.
{{Pre}}
# 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 
</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.
 
= 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/. [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>
chromium --proxy-server="10.130.5.180:3128"
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
</pre>
</pre>


==== Vivaldi ====
= lzma =
Based on Chromium.
* 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.


A sidebar provides a place to quickly access your bookmarks, downloads, and history. Less standard is the built-in ability to write and save notes, also available in the sidebar.
= squashfs =
[[Filesystem|squashfs]]


While cool, Vivaldi is also a proprietary browser.
= List contents of tar.gz or tar.bz2 =
<pre>
tar -tzvf myfile.tar.gz


The proxy setting is not found in the latest version. [https://forum.vivaldi.net/topic/8100/vivaldi-proxy-settings/4 To use it],
tar -tjvf myfile.tar.bz2  # replace z with j
</pre>
 
== gzip: stdin: not in gzip format ==
I got the following message when I try to run tar -xzvf or tar -tzvf command.
<pre>
<pre>
$ vivaldi --proxy-server="127.0.0.1:8118"
$ 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
</pre>
</pre>
The answer is [https://itsfoss.com/how-solve-stdin-gzip-format/ How to solve: stdin: not in gzip format].


To uninstall it, open the package manager to remove it.
Solution: Since it was not a gzipped file, a simple tar is able to extract the file: ''tar xvf MyFile.tar.gz ''


==== Opera ====
= Extract files, AVFS =
Based on Chromium.
See [[Extract_files|Extract files]].


Like Chrome, Opera is closed source.  
= Show folder size for one level only =
<pre>
du --max-depth=1 -h
</pre>
The graphical tool is called '''Disk Usage Analyze''' which is already available on Ubuntu.


==== [https://wiki.gnome.org/Apps/Web GNOME Web] ====
= Soft link and hard link =
There are browsers made specifically for Linux, and GNOME Web is the most mature of the bunch.
== Soft link ==
<pre>
ln -s /full/path/of/original/file /full/path/of/soft/link/file
</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]
 
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]].
 
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.


It looks and feels like a program intended to run on Linux.
== Hard link ==
[https://unix.stackexchange.com/a/65003 What's the difference between a hard links and copied files?]


Web lacks the kind of extensions you see on Chrome and Firefox (though ad-block does come built-in).
* [https://askubuntu.com/a/525129 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
{{Pre}}
echo "abcd" > foo
ln foo foo2
ls -l foo*
echo "efgh" >> foo2
cat foo
rm foo
cat foo2
</pre>


==== [https://gitlab.gnome.org/gnumdk/eolie Eolie] ====
= Self-hosted servers =
Eolie is another browser built specifically for GNOME.
* 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.
* [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.


The URL bar shows a site’s title rather than the web address.
== 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.


==== [https://www.brave.com/ Brave] - private, secure, support Chrome extensions ====
= DNS =
https://en.wikipedia.org/wiki/Brave_(web_browser)
[[DNS|DNS]]


The browser uses a fork of [https://github.com/electron/electron Electron], called [https://github.com/brave/muon Muon], designed with a focus on browser features. For example, it has support for Chrome extensions, and a higher level of security.
Port number is 53. An example is [[Raspberry#Pi-hole|Pi-hole]].


[https://github.com/brave/browser-laptop/issues/3756 Lacks the in-browser proxy] (even version 0.57)
= Email server =
See [[Mail_server|Mail_server]].


[https://www.ithome.com.tw/news/127698 Chromium版隱私瀏覽器Brave 0.57出爐了,要給你Chrome方便性但不回傳資料給Google], [https://www.zdnet.com/article/brave-browser-moves-to-chromium-codebase-now-supports-chrome-extensions/ Brave browser moves to Chromium codebase, now supports Chrome extensions] Dec 2018
= Backup =
See [[Backup|Backup]].


==== [http://midori-browser.org/ Midori] ====
= at command: Schedule a task =
* [https://opensource.com/article/21/8/linux-at-command Schedule a task with the Linux at command]
* [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


==== [https://www.falkon.org/ Falkon] and formally [https://github.com/QupZilla/qupzilla Qupzilla] ====
$ echo "command_to_be_run" | at 09:00
QupZilla is a new and very fast QtWebEngine browser. It aims to be a ''lightweight'' web browser available through all major platforms.


[https://en.wikipedia.org/wiki/Falkon Wikipedia]. Download: only Windows and Linux binaries are available.
$ atq  # list of jobs


When I tested Falkon-3.0.1.AppImage - for 64-bit Linux on Mint 18.3, it gives an error <pre>10:39AM ~/Downloads$ ./Falkon-3.0.1.AppImage
$ atrm 6  # delete the 6th job
QApplication: invalid style override passed, ignoring it.
Could not find QtWebEngineProcess
</pre>
</pre>


=== Filezilla ===
= Cron job by root =
[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.
Note that there is a "user" field for cron jobs defined in /etc/crontab or /etc/cron.d.
 
<ul>
=== The device is busy ===
<li>Place one: '''/etc/crontab''' and '''/etc/cron.daily, /etc/cron.hourly, /etc/cron.monthly, /etc/cron.weekly'''.  
* http://oletange.blogspot.com/2012/04/umount-device-is-busy-why.html
<pre>
<pre>
brb@brb-P45T-A:~$ sudo umount /media/brb/TOSHIBA
cat /etc/crontab
[sudo] password for brb:
# How to List Daily Cron Jobs
umount: /media/brb/TOSHIBA: device is busy.
ls -la /etc/cron.daily
        (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>
</pre>


* See http://ocaoimh.ie/2008/02/13/how-to-umount-when-the-device-is-busy/
<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?]
<pre>
</ul>
# fuser -m /dev/sdc1
 
/dev/sdc1: 538
= Running a cron job as a user =
# ps auxw|grep 538
== Some examples ==
donncha 538 0.4 2.7 219212 56792 ? SLl Feb11 11:25 rhythmbox
* http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
* https://crontab.guru/examples.html and [https://crontab.guru/tips.html tips]
* Can I break a line cron command into multiple lines? No. Creating another script file in this case.
* A specific time
{{Pre}}
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>
</pre>
Another handy one is:
* 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>
<pre>
umount -l /dev/sdwhatever
*/10 * * * * /home/ramesh/check-disk-space
</pre>
</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


=== Kill a process and the '''pstree''' command ===
# Will only run on even days:
<syntaxhighlight lang='bash'>
0 0 2-30/2 * * command
# find the PID
</pre>
pgrep ProgramName
# Kill the ProgramName process
kill -9 PID
</syntaxhighlight>


Another command is '''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.
== crontab ==
* [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>


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].
Make sure the .sh file gives a complete path. For example,
<pre>
#!/bin/sh
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>


[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.
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.


[https://www.howtoforge.com/linux-pkill-command/ pkill] command. For example, ''pkill gedit''.
== GUI ==
[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)]


=== Format a USB drive ===
== PATH and Shell ==
[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])
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.  
 
{{Pre}}
This is a GUI application. After the installation, search "USB Stick Formatter".
$ cat syncIP
 
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
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.
</pre>
 
and the cron job
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.
<syntaxhighlight lang='bash'>
sudo mkfs.exfat -n Staples /dev/sdc1
</syntaxhighlight>
 
Note that '''fdisk''' or '''sfdisk''' cannot differentiate NTFS/exFAT. But [https://en.wikipedia.org/wiki/Cfdisk cfdisk] or '''GParted''' can.
<syntaxhighlight lang='bash'>
sudo cfdisk /dev/sdX
</syntaxhighlight>
 
=== Create an ext3 file system on a USB flash drive ===
<pre>
<pre>
umount /dev/sdb1  (depending on the device of course)
06 15 * * * /home/MYUSERNAME/Ubuntu\ One/syncIP > $HOME/Ubuntu\ One/ip.txt 2>&1
sudo mkfs.ext3 /dev/sdb1
sudo e2label /dev/sdb1 usbdrive  (change the label)
</pre>
</pre>
We can create MS-DOS file system by
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 ==
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])
<pre>
<pre>
sudo mkfs.vfat /dev/sdb1
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.


=== Add a new user with home directory ===
== 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>
<pre>
adduser xxx
@reboot sleep 300 && python /home/pi/startup_mailer.py
</pre>
</pre>
 
</li>
'''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.
<li>[https://github.com/martinwoodward/PumpkinPi pausing for 10 seconds before running the python script]
 
To delete the user and home directory, use
<pre>
<pre>
deluser --remove-home xxx
@reboot /bin/sleep 10 ; /usr/bin/python /home/pi/PumpkinPi/src/pumpkinpi.py &
</pre>
</pre>
</li>
</ul>
=== rc.local ===
[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]


To view the user information, type '' '''id USERNAME''' '' or ''cat /etc/passwd''.
= 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.


=== gzip with multi cores ===
== Display and back up cron jobs ==
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.
[https://www.cyberciti.biz/faq/linux-show-what-cron-jobs-are-setup/ Linux List / Display and view all cron jobs]
<syntaxhighlight lang="bash">
sudo apt-get install pigz
pigz -9 FILENAME  # compress & convert the file to FILENAME.gz


tar cf - paths-to-archive | pigz -9 -p 12 > archive.tar.gz
== Check log ==
</syntaxhighlight>
'''sudo grep CRON /var/log/syslog --color'''
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).
== Anacron ==
Anacron keeps track of the last time a task was run, and if it was missed, it runs it.


=== Compress a folder without full path name ===
Anacron typically runs daily, while cron runs every minute.
Suppose we want to compress the folder ~/Documents and its subfolders. We want to include Documents folder name but not /home/brb/Documents name.
<pre>
<syntaxhighlight lang="bash">
cat /etc/anacrontab
# Method 1. Include 'Documents' as the top folder name
</pre>
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
= GUI cron =
tar -tzvf tmp.tar.gz 
* [https://www.ostechnix.com/how-to-easily-and-safely-manage-cron-jobs-in-linux/ How To Easily And Safely Manage Cron Jobs In Linux]
</syntaxhighlight>
* [https://github.com/alseambusher/crontab-ui Crontab UI]
* http://corntab.com/#!


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.
= md5sum =
[https://www.howtoforge.com/linux-md5sum-command/ Linux md5sum Command Explained For Beginners (5 Examples)]


=== squashfs ===
How to verify files?
'''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>
md5sum file1.txt file2.txt file3.txt > hashes
md5sum --check hashes
</pre>


* https://en.wikipedia.org/wiki/SquashFS
= fsck =
* http://squashfs.sourceforge.net/
* [https://www.cyberciti.biz/tips/repairing-linux-ext2-or-ext3-file-system.html Repairing Linux ext2 or ext3 or ext4 File System (fsck)]
* http://elinux.org/Squash_FS_Howto
* [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]


<syntaxhighlight lang="bash">
== Fsck error on boot ==
# create a squashfs file
[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]
sudo mksquashfs /etc test.squashfs


# mount the squashfs file
This happened when I resize an Ubuntu partition.  
mkdir /mnt/squash
mount -o loop compressedfs.squashfs /mnt/squash
# you can acess the contents at /mnt/squashfs


# exclude files
fsck -fy /dev/sda1
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 or tar.bz2 ===
== Force fsck on the Next Reboot or Boot Sequence ==
<pre>
https://www.linuxuprising.com/2019/05/how-to-force-fsck-filesystem.html
tar -tzvf myfile.tar.gz


tar -tjvf myfile.tar.bz2  # replace z with j
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.
{{Pre}}
sudo touch /forcefsck
</pre>
</pre>


=== Extract files ===
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]].
==== Extract tar.gz or zip to a specified directory ====
<syntaxhighlight lang='bash'>
tar xzvf XXXX.tar.gz -C DIRECTORY
# single or double quotes will give an error
#
# tar xzvf ~/Downloads/inSilicoDb_2.7.0.tar.gz -C "~/Downloads"
# tar: ~/Downloads: Cannot open: No such file or directory
# tar: Error is not recoverable: exiting now
# $ tar xzvf ~/Downloads/inSilicoDb_2.7.0.tar.gz -C '~/Downloads'
# tar: ~/Downloads: Cannot open: No such file or directory
# tar: Error is not recoverable: exiting now


unzip XXX.zip -d DIRECTORY
== Can I run fsck or e2fsck when Linux file system is mounted? ==
</syntaxhighlight>
https://www.cyberciti.biz/faq/can-i-run-fsck-or-e2fsck-when-linux-file-system-is-mounted/


==== Extract gz file but keep the original gz file ====
== What is the difference between fsck and e2fsck? ==
<syntaxhighlight lang="bash">
https://superuser.com/a/19984
gunzip -c x.txt.gz > x.txt
</syntaxhighlight>
'''gunzip -c''' which simply writes the output stream to stdout


==== Extract .xz file ====
= Swap partition =
<syntaxhighlight lang="bash">
* [https://www.howtogeek.com/455981/how-to-create-a-swap-file-on-linux/ How to Create a Swap File on Linux]
xz -d archive.xz
* [https://www.tecmint.com/disable-swap-partition-in-centos-ubuntu/ How to Permanently Disable Swap in Linux]
</syntaxhighlight>


==== Extract tar.xz file ====
== Swap file vs swap partition ==
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://www.jetsonhacks.com/2019/04/25/jetson-nano-run-on-usb-drive/ Jetson Nano – Run on USB Drive]


<syntaxhighlight lang="bash">
= Mount drive, add a new hard drive =
tar xf archive.tar.xz
* [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]
tar xf archive.tar.gz
* Videos
</syntaxhighlight>
** [https://youtu.be/2Z6ouBYfZr8 Linux Crash Course - Formatting & Mounting Storage Volumes]
** [https://youtu.be/A7xH74o6kY0 Linux Crash Course - The /etc/fstab file]


==== Extract tar.bz2 file ====
== /etc/fstab and blkid ==
<syntaxhighlight lang="bash">
See [[Fstab]].
tar -xjvf archive.tar.bz2  # replace z with j as we compare it to tar.gz file
</syntaxhighlight>


==== How To Extract and Decompress a .bz2/.tbz2 File ====
== autofs, /etc/auto.master ==
See [http://www.cyberciti.biz/faq/linuxunix-how-to-extract-and-decompress-a-bz2-tbz2-file/ this article] from cyberciti.biz.
[https://opensource.com/article/18/7/network-attached-storage-Raspberry-Pi Building a network attached storage device with a Raspberry Pi]
<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>


==== 10 Basic Encryption Terms Everyone Should Know and Understand ====
== Fix a malfunctioning USB device or port ==
https://www.makeuseof.com/tag/encryption-terms/
[https://www.makeuseof.com/tag/fix-usb-device-port-linux/ 5 Ways to Fix a Malfunctioning USB Device or Port on Linux]


==== How to Encrypt and Decrypt Files and Directories Using Tar and OpenSSL ====
== Check the physical health of a USB stick ==
http://www.tecmint.com/encrypt-decrypt-files-tar-openssl-linux/
[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]


==== How to install and use 7zip file archiver ====
== USB drive ==
https://www.howtoforge.com/tutorial/how-to-install-and-use-7zip-file-archiver-on-ubuntu-linux/
* [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?]


==== Compare zip, tar.xz, tar.gz, 7z ====
Run the following to confirm the USB device is detected.  
The compression rate comparison is (from best to worst) 7z > tar.xz > tar.gz > zip.
{{Pre}}
sudo fdisk -l
# OR
dmesg | grep -i "SCSI"
</pre>


For example, consider qt-everywhere-opensource-src-5.5.0 from http://download.qt.io/official_releases/qt/5.5/5.5.0/single/
Now suppose the usb device is found in '''dev/sdb1'''.  
* zip 540M
{{Pre}}
* tar.xz 305M
sudo mkdir /mnt/usb
* tar.gz 436M
sudo mount -t vfat -o rw,users /dev/sdb1 /mnt/usb
* 7z 297M
</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>


==== Extract one files from tar.gz ====
At the end, run umount command like
Extract a file called etc/default/sysstat from config.tar.gz tarball:
{{Pre}}
<syntaxhighlight lang="bash">
sudo umount /mnt/usb
$ tar -zxvf config.tar.gz etc/default/sysstat
</pre>
</syntaxhighlight>
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]
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>


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:
== Mount an iso file ==
<syntaxhighlight lang="bash">
* http://www.shellhacks.com/en/Mounting-an-ISO-Image-in-Linux
$ tar -xf cbz.tar --wildcards --no-anchored 'pic*'
{{Pre}}
</syntaxhighlight>
sudo mkdir -p /mnt/mount_point # create a mount point
To extract all php files, enter:
sudo mount -o loop /home/user/disk.iso /mnt/mount_point
<syntaxhighlight lang="bash">
mount  # verify
$ tar -xf cbz.tar --wildcards --no-anchored '*.php'
</pre>
</syntaxhighlight>


==== remove leading directory components on extraction with tar ====
== Mount remote Windows share ==
* [https://serverfault.com/questions/330127/tar-remove-leading-directory-components-on-extraction --strip-components] option
* http://www.shellhacks.com/en/HowTo-Mount-Remote-Windows-Partition-Share-under-Linux
* Real examples
** [https://github.com/wikimedia/mediawiki-docker/blob/2dea40647eb85d6e0fc607904e0779644cf869c9/stable/Dockerfile Strip the top directory after extracting mediawiki tar ball]. "tar -xz --strip-components=1 -f mediawiki.tar.gz"


==== [https://github.com/lb1a/avfs AVFS] and [https://github.com/bramp/archivemount Archivemount] ====
== Sharing files with Windows by using NitroShare ==
If we want to extract certain files from a tarballj/archive, it is more efficient to use a virtual filesystem like AVFS. PS. for a large archive file, even extracting only a single file at the top directory it is terribly slow if we use the '''tar''' command directly.
[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.


Before we install the utility, let's look at the package dependecies of AVFS and Archivemount.
== NTFS usb drive in xubuntu ==
<syntaxhighlight lang="bash">
http://xflinux.blogspot.com/2011/01/mount-ntfs-volumes-automatically-in.html
$ apt-cache showpkg archivemount
<pre>
Package: archivemount
sudo apt-get install ntfs-config
Versions:
</pre>
0.8.1-1 (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_binary-amd64_Packages)
Now go to Applications>> System>> Ntfs Configuration Tool
Description Language:
                File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_binary-amd64_Packages
                  MD5: d6302be9f06a91afa32326ab175e2086
Description Language: en
                File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_i18n_Translation-en
                  MD5: d6302be9f06a91afa32326ab175e2086


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).


Reverse Depends:
Make sure the " Enable write support for internal devices" option is selected. Now click Close.
  archivemount:i386,archivemount
Dependencies:
0.8.1-1 - libarchive13 (0 (null)) libc6 (2 2.4) libfuse2 (2 2.8.1) fuse (2 2.8.5-2) archivemount:i386 (0 (null))
Provides:
0.8.1-1 -
Reverse Provides:
brb@T3600 ~ $ apt-cache showpkg avfs
Package: avfs
Versions:
1.0.1-2 (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_binary-amd64_Packages) (/var/lib/dpkg/status)
Description Language:
                File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_binary-amd64_Packages
                  MD5: bce08fbc36fd7b8e3c454f36f0daf699
Description Language: en
                File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_universe_i18n_Translation-en
                  MD5: bce08fbc36fd7b8e3c454f36f0daf699


== Many drives, one folder ==
* [http://www.linuxjournal.com/content/many-drives-one-folder mhddfs] program.


Reverse Depends:
== Partition tables ==
  avfs:i386,avfs
[http://www.makeuseof.com/tag/partition-table-edit-error/ Partition Tables and the Dangers of Editing Them]
  worker,avfs
Dependencies:
1.0.1-2 - libc6 (2 2.14) libfuse2 (2 2.8.1) fuse (0 (null)) unzip (0 (null)) zip (0 (null)) arj (0 (null)) lha (0 (null))
zoo (0 (null)) rpm (0 (null)) p7zip (16 (null)) p7zip-full (0 (null)) cdparanoia (0 (null))
wget (0 (null)) avfs:i386 (0 (null))
Provides:
1.0.1-2 -
Reverse Provides:
</syntaxhighlight>


Install it now.
== parted command ==
<syntaxhighlight lang="bash">
[https://opensource.com/article/18/6/how-partition-disk-linux How to partition a disk in Linux]
sudo apt-get install avfs
mountavfs
# Assume MyFile.tar.gz exists in the current directory
ls ~/.avfs/$PWD/MyFile.tar.gz#     
# Alternatively, browse the content in Nautilus, but you need to add a trailing # character by hand to the path
# (Ctrl-L to access the address bar).
...
cat ~/.avfs/$PWD/MyFile.tar.gz#/README
# another tarball
ls ~/.avfs/$PWD/MyFile2.tar.gz#     
umountavfs
</syntaxhighlight>


* [https://en.wikipedia.org/wiki/Filesystem_in_Userspace Filesystem in Userspace (FUSE)]
== Recommended partition schemes ==
* [http://www.ibm.com/developerworks/linux/library/l-fuse/ Develop your own filesystem with FUSE]
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s2-diskpartrecommend-x86.html Redhat]
* [https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ubuntu%20mount%20tar.gz%20file Google: ubuntu mount tar.gz file] which gives many choices like '''[https://en.wikipedia.org/wiki/Archivemount archivemount]'''.
* [https://www.debian.org/releases/stable/i386/apcs03.html.en Debian]
* [http://buechse.de/HOWTO/avfs_fuse_and_apache/ HOWTO: setup avfs / fuse on 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, avfs sometimes does not work:( In this case, Ubuntu's Archive Manager does work. Maybe the file is too large.
== HOME /home directory ==
<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+ */ " >
[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]
brb@T3600 ~/Downloads $ time ls ~/.avfs/$PWD/Homo_sapiens_UCSC_hg19.tar.gz#/
ls: cannot access /home/brb/.avfs//home/brb/Downloads/Homo_sapiens_UCSC_hg19.tar.gz#/nown exact 1 SingleClassTriAllelic,InconsistentAlleles 2 1000GENOMES,SSMP, 2 A,T, 22.000000,2274.000: Input/output error
ls: cannot access /home/brb/.avfs//home/brb/Downloads/Homo_sapiens_UCSC_hg19.tar.gz#/chr12 25482890 rs544684287 G A 0 . molType=genomic;class=single
chr12 25482914 rs558575390 T G 0 . m: Input/output error
000,?0.999500,0.000500,??797?chr3?27877637?27877638?rs1478557?0?+?G?G?A
4?rs555100828?0?+?T?T?C
76?chr2?103777623?103777624?rs181283085?0?+?A?A?A
chr12?25482890?rs544684287?G?A?0?.?molType=genomic;class=single?chr12?25482914?rs558575390?T?G?0?.?m
G?A
Homo_sapiens
nown?exact?1?SingleClassTriAllelic,InconsistentAlleles?2?1000GENOMES,SSMP,?2?A,T,?22.000000,2274.000
README.txt
T?C


real 25m51.340s
== /var directory filled up ==
user 0m0.000s
[https://linuxconfig.org/how-to-move-var-directory-to-another-partition How to move /var directory to another partition]
sys 0m0.003s
{{Pre}}
brb@T3600 ~/Downloads $ ls ~/.avfs/$PWD/annovar.latest.tar.gz#/
blkid | grep sdc1  # get UUID
annovar
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>
</pre>
Reboot


For archivemount, see [http://www.linux-mag.com/id/7825/ Cool User File Systems: ArchiveMount]
== Why put things other than /home to a separate partition? ==
<syntaxhighlight lang="bash">
[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?]
archivemount files.tgz mntDir
 
umount mntDir
The /var partition is used by Docker and Apache.
</syntaxhighlight>
 
[https://unix.stackexchange.com/a/84764 /home, /boot and /var partitions] can be separated.
 
= Process/job =


=== Show folder size for one level only ===
== 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>
du --max-depth=1 -h
ps -C shutter # Listing only a Process by Command
</pre>
              # Adding the 'watch' command to show the process in real-time
The graphical tool is called '''Disk Usage Analyze''' which is already available on Ubuntu.
ps -C dd --format pid,cmd,%cpu # Show PID, CMD and %CPU


=== Soft link ===
sudo ps -p {PID} -o pid,cmd,lstart,etimes,etime
<pre>
ln -s /full/path/of/original/file /full/path/of/soft/link/file
</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]


=== Self-hosted servers ===
ps -e | less # Listing Process for All Users
* 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.
* [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.


=== DNSCrypt ===
ps -eH --forest | less # hierarchy
* https://en.wikipedia.org/wiki/DNSCrypt
* [https://github.com/jedisct1/dnscrypt-proxy dnscrypt-proxy 2 - A flexible DNS proxy, with support for encrypted DNS protocols]
* [https://www.linuxuprising.com/2018/10/install-and-enable-dnscrypt-proxy-2-in.html Install and Enable DNSCrypt Proxy 2 in Ubuntu 18.04 Or 18.10 / Debian Unstable Or Testing]


=== DNS server ===
ps -e | grep firefox # Listing Processes by Name
* [https://opensource.com/article/17/4/introduction-domain-name-system-dns Introduction to the Domain Name System (DNS)]
* [https://opensource.com/article/17/4/build-your-own-name-server Build your own DNS name server on Linux]


==== setup ====
ps -p 3403 # Listing Processes by Process ID
* https://support.rackspace.com/how-to/changing-dns-settings-on-linux/
* https://helix.nih.gov/user_guides/kerb5_config.html


=== DNSmasq (DNS + DHCP server) ===
ps -u mary  # Listing Processes Owned by a User
* [http://www.thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html Man page] and [http://www.thekelleys.org.uk/dnsmasq/docs/setup.html Setup]
* [https://www.linux.com/learn/dnsmasq-easy-lan-name-services Dnsmasq For Easy LAN Name Services]
* https://wiki.archlinux.org/index.php/dnsmasq
* https://wiki.debian.org/HowTo/dnsmasq
* http://www.linuxjournal.com/content/dnsmasq-pint-sized-super-d%C3%A6mon
* https://blogging.dragon.org.uk/howto-setup-dnsmasq-as-dns-dhcp/


==== Local forwarding server ====
sudo pkill top # Killing Processes by Name
dnsmasq program is running on my Ubuntu and Linux/Mint machines.


See [https://askubuntu.com/questions/627899/nameserver-127-0-1-1-in-resolv-conf-wont-go-away nameserver 127.0.1.1 in resolv.conf won't go away!]
sudo killall top # Killing Multiple Processes by Name
<syntaxhighlight lang='bash'>
</pre>
$ ps -ef | grep -i dnsmasq


$ sudo netstat -anp | grep -i dnsmasq
== Kill a process and the '''pstree''' command ==
</syntaxhighlight>
* 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>
sudo killall -u USERNAME
</pre>
</li>
</ul>
* [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.
* [https://www.howtoforge.com/linux-pkill-command/ pkill] command. For example, ''pkill gedit''.


=== Change DNS setting ===
== How to Kill Zombie Processes on Linux ==
* [https://www.makeuseof.com/tag/change-dns-increase-internet-speed/ Why Changing DNS Settings Increases Your Internet Speed], [https://www.makeuseof.com/tag/best-dns-providers-security/ 5 DNS Servers Guaranteed to Improve Your Online Safety]
[https://www.howtogeek.com/701971/how-to-kill-zombie-processes-on-linux/ How to Kill Zombie Processes on Linux]
** https://1.1.1.1/, [https://www.ithome.com.tw/news/122215 隱私優先、速度最快,公共DNS服務1.1.1.1上線了]
** Google: 8.8.8.8 and 8.8.4.4
** OpenDNS: 208.67.220.220 and 208.67.222.222
** DNS Watch:  84.200.69.80 and 84.200.70.40
** OpenNIC: 206.125.173.29 and 45.32.230.225
** UncensoredDNS: 91.239.100.100 and 89.233.43.71
* [https://www.safervpn.com/support/articles/115000327609-Change-DNS-Settings-on-Windows-Mac-Android-IOS-Linux Change DNS Settings on Windows / Mac / Android / IOS / Linux]
* [https://websiteforstudents.com/setup-cloudflare-dns-on-ubuntu-16-04-17-10-18-04-desktop/ Setup CloudFlare DNS On Ubuntu 16.04 / 17.10 / 18.04 Desktop]
*# Open Ubuntu Network Manager (System settings > Network > Settings > Wired or Wireless or both)
*# Select both IPv4 and IPv6 and turn off automatic DNS IP settings… then type the custom Cloudflare DNS IP addresses you want to use…
* [https://www.makeuseof.com/tag/cloudflare-1111-dns-mobile/ You Can Now Use Cloudflare’s 1.1.1.1 DNS on Mobile]


==== Query DNS server ====
== Simulate/produce high cpu load ==
To [https://askubuntu.com/questions/152593/command-line-to-list-dns-servers-used-by-my-system list the current DNS servers used by my system],
[https://superuser.com/a/443409 How can I produce high CPU load on a Linux server?]
<pre>
# method 1:
sudo apt install stress
stress --cpu 3


Method 1:
# method 2:
<syntaxhighlight lang='bash'>
for i in 1 2 3 ; do while : ; do : ; done & done
# Ubuntu >= 15
jobs  # list background jobs
$ nmcli device show <interfacename> | grep IP4.DNS
for i in 1 2 3 4; do kill %$i; done  # kill "job" (not "PID") 1,2,3,4
# Ubuntu <= 14
</pre>
$ nmcli dev list iface <interfacename> | grep IP4
</syntaxhighlight>


Method 2:
== ps, pgrep and pidof: How much resource is used by a process ==
<syntaxhighlight lang='bash'>
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
$ cat /etc/resolv.conf
{{Pre}}
</syntaxhighlight>
ps -p <pid> -o %cpu,%mem,cmd
</pre>
For example,
{{Pre}}
$ 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
</pre>


Another way is to use the R packages: [https://cran.r-project.org/web/packages/gdns/index.html gdns] and [https://github.com/hrbrmstr/dnsflare dnsflare]. [https://rud.is/b/2018/04/01/more-options-for-querying-dns-from-r-with-1-1-1-1/ More Options For Querying DNS From R with 1.1.1.1].
'''pgrep'''
{{Pre}}
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
</pre>


==== 3 Ways to Check DNS Propagation Status ====
'''pidof'''
https://www.makeuseof.com/tag/check-dns-propagation-status/
{{Pre}}
08:49AM ~$ pidof firefox
27951 25961 25612 25486
08:51AM ~$ pidof /usr/lib/firefox/firefox
27951 25961 25612 25486


=== Email server ===
$ kill $(pidof firefox)
==== POP, IMAP and Exchange ====
</pre>
* https://support.office.com/en-US/article/What-are-IMAP-and-POP-ca2c5799-49f9-4079-aefe-ddca85d5b1c9?ui=en-US&rs=en-US&ad=US&fromAR=1
* https://www.howtogeek.com/99423/email-whats-the-difference-in-pop3-imap-and-exchange/


'''POP''' works by contacting your email service and downloading all of your new messages from it. Once they are downloaded onto your PC or Mac, they are deleted from the email service.
== All You Need To Know About Processes in Linux ==
http://www.tecmint.com/linux-process-management/


'''IMAP''' allows you to access your email wherever you are, from any device. When you read an email message using IMAP, you aren't actually downloading or storing it on your computer; instead, you're reading it from the email service. As a result, you can check your email from different devices, anywhere in the world: your phone, a computer, a friend's computer.
== run commands in a background and allow log off ==
{{Pre}}
nohup /path/to/script >output 2>&1 &
</pre>


'''Exchange''' offers the same syncing capabilities as IMAP, plus much more. Exchange is a Microsoft product, giving you the ability to still use Outlook as your email service and benefit from Exchange functionality.
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>


==== Configure Postfix to use Gmail as a Mail Relay ====
See also [https://en.wikipedia.org/wiki/Process_substitution#Anonymous_named_pipe Anonymous named pipe].
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/


==== How to Build an Email Server on Ubuntu Linux ====
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.
* https://www.linux.com/learn/how-build-email-server-ubuntu-linux, [https://www.linux.com/learn/sysadmin/building-email-server-ubuntu-linux-part-3 Part 2] & [https://www.linux.com/learn/sysadmin/building-email-server-ubuntu-linux-part-3 Part 3]
* https://help.ubuntu.com/community/Postfix
* https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-14-04
* https://www.digitalocean.com/community/tutorials/how-to-install-and-setup-postfix-on-ubuntu-14-04


==== Webmail ====
== job: How do I send an already-running process into the background ==
[https://www.howtoforge.com/tutorial/install-webmail-lite-on-debian-9/ Install WebMail Lite PHP based Webmail Client on Debian 9.1]
* [https://www.makeuseof.com/run-linux-commands-in-background/ How to Run Linux Commands in the Background]
* http://stackoverflow.com/questions/625409/how-do-i-put-an-already-running-process-under-nohup
* [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]


==== [http://caspian.dotconf.net/menu/Software/SendEmail/ sendemail] package ====
Steps:
* http://bhfsteve.blogspot.com/2013/03/monitoring-web-page-for-changes-using.html
# '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 sendemail'''
# '''bg''' to run it in the background.
* Usage
# '''jobs -l''' to get the jobID and process ID
<syntaxhighlight lang='bash'>
# '''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.
sendEmail -f $USERNAME -s smtp.gmail.com:587 \
            -xu $USERNAME -xp $PASSWORD -t $USERNAME \
            -o tls=yes \
            -u "Web page changed" \
            -m "Visit it at $URL"


sendEmail -f YourEmail@gmail.com -t SomeoneYoureEmailing@domain.com \
== Stopped job ==
            -s smtp.gmail.com:587 -xu [email protected] -xp YOURPASSWORD \
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.
            -o tls=yes \
            -u "Hello from sendEmail" \
            -m "How are you? I'm testing sendEmail from the command line."
</syntaxhighlight>


==== Kolab ====
* '''jobs -s''' showing stopped jobs
[https://www.howtoforge.com/tutorial/install-and-configure-kolab-groupware-on-ubuntu-1604/ Install and Configure Kolab Groupware on Ubuntu 16.04 LTS]
* '''jobs -l''' showing the job PID


==== Criptext: private email service ====
[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.
* https://www.criptext.com/
* '''fg %1''' move the stopped job ID #1 to the foreground (works)
* https://www.linuxuprising.com/2018/10/criptext-is-new-encrypted-email-service.html
* '''kill %1''' # kill job ID #1
* '''kill 12345''' # kill job PID 12345
* '''kill -9 `jobs -ps`''' may not work
* '''kill -9 $(jobs -p)'''


==== Zimbra ====
== nice ==
[https://www.howtoforge.com/tutorial/install-zimbra-collaboration-suite-88-on-ubuntu/ How to Install Zimbra Collaboration Suite 8.8 on Ubuntu]
[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]


=== Backup ===
== watch command ==
# [http://rdiff-backup.nongnu.org/index.html rdiff-backup]. See
[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/
#* [https://opensource.com/life/16/3/turn-your-old-raspberry-pi-automatic-backup-server Turn your old Raspberry Pi into an automatic backup server]
#* [https://www.tecmint.com/rdiff-backup-remote-incremental-backup-for-linux/ rdiff-backup – A Remote Incremental Backup Tool for Linux]
# Use a 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
We can use the '''watch''' command to monitor a specific process such as the progress of the ''dd'' command.


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.
Terminal 1
 
<pre>
I install it under
watch -n 10 who
'''~/Downloads/andreafabrizi-Dropbox-Uploader-cdc2466 directory'''
watch ps -C dd --format pid,cmd,%cpu
 
</pre>
Instruction with screenshots: http://www.jobnix.in/dropbox-command-line-interface-cli-client/


Sample usages:
Terminal 2
<pre>
<pre>
./dropbox_uploader.sh  list /
dd if=/dev/zero of=/dev/null
./dropbox_uploader.sh  upload ~/Desktop/ConfigurateNote.txt
</pre>
</pre>


==== Clone ====
Use '''--color''' for [https://stackoverflow.com/a/3794222 color output].
[https://www.makeuseof.com/tag/2-methods-to-clone-your-linux-hard-drive/ 4 Methods To Clone Your Linux Hard Drive ]
# dd can clone an entire HDD or disk partition
# Partimage. partimage does not support the ext4 filesystem
# Partclone
# Clonezilla


==== back up DVDs ====
== while + sleep ==
<syntaxhighlight lang='bash'>
[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,
$ df
$ sudo dd if=/dev/sr0 of=filename.iso status=progress
# Don't add the 'bs' parameter or you'll get an error reading '/dev/sr0': Input/output error
</syntaxhighlight>


==== [https://opensource.com/article/18/7/how-use-dd-linux back up a remote drive using SSH and save the resulting archive to your local machine] ====
== ulimit ==
<syntaxhighlight lang='bash'>
* [https://www.cyberciti.biz/faq/how-to-find-ulimit-for-user-on-linux/ How to find ulimit for user on Linux]
# ssh username@54.98.132.10 "dd if=/dev/sda | gzip -1 -" | dd of=backup.gz
* [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]
</syntaxhighlight>
where "-1" (one) indicates the fastest compression method and the dash means ‘standard input’.


==== Backups vs. Archives ====
= Notepadqq - Notepad++-like editor =
[https://www.howtogeek.com/356473/how-to-archive-your-data-for-virtually-forever/ How to Archive Your Data (Virtually) Forever]
[http://www.ubuntugeek.com/notepadqq-the-linux-source-editor.html Notepadqq]. It is written using Qt. It does not have printing function:(


==== Delete files or directories older than XXX days ====
= Note apps that can sync =
Suppose we have a cron job to run backup and that creates a lot of directories. We like to erase them to avoid our system running out of space. You can run a space-checking program that'll alert you when the filesystem is low on free space. In addition we can run a cron job that uses ''find'' to erase all files.
[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.
<syntaxhighlight lang='bash'>
cp -p -r ~/Downloads/SomeOldDirectory /tmp/
ls -lt /tmp
# List only
# Older than 2 days. Note the plus sign after "-mtime".
# Quotes in "{}" is to deal with names with spaces
find /tmp -type d -mtime +2 -exec ls -ld "{}" +


find /tmp -type d -mtime +2 -exec rm -rf "{}" + 
= Evernote =
# Or if we don't mind some extra warning messages
== Evernote alternative ==
# find /tmp -type d -mtime +2 -exec rm -rf "{}" \;
[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]
ls -lt /tmp
</syntaxhighlight>
See
* [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]
* [https://serversitters.com/how-to-delete-all-files-before-a-certain-date-in-linux.html How to delete all files before a certain date in Linux]
* [https://www.linuxjournal.com/content/avoiding-server-disaster Avoding server disaster]


==== [http://www.teejeetech.in/p/timeshift.html Timeshift] ====
== Backup/restore Evernote ==
* [https://itsfoss.com/backup-restore-linux-timeshift/ How To Backup And Restore Linux With Timeshift]
https://www.makeuseof.com/tag/backup-restore-evernote/
* [https://linuxhint.com/timeshift-backup-tutorial/ Linux TimeShift for Backup Tutorial]


==== CloudBerry ====
= Markdown =
[https://www.makeuseof.com/tag/cloudberry-backup-protects-files-on-windows-mac-and-linux/ CloudBerry Backup Protects Files on Windows, Mac, and Linux]
== 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.  
==== Github, Bitbucket, Gitlab ====
* http://stackoverflow.com/questions/9843609/view-markdown-files-offline. [https://github.com/joeyespo/grip Grip] works fine.
We can use these git services to get real-time data (eg temperature, IP, etc).
{{Pre}}
 
sudo pip install grip
=== Running a cron job as a user ===
grip readme.md
==== Some examples ====
* http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
* https://crontab.guru/examples.html and [https://crontab.guru/tips.html tips]
* A specific time
<pre>
MIN HOUR DOM MON DOW CMD
30 08 10 06 * /home/ramesh/full-backup
#  30 – 30th Minute
#  08 – 08 AM
#  10 – 10th Day
#  06 – 6th Month (June)
#  * – Every day of the week
</pre>
</pre>
* Twice a day
* 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>
<pre>
00 11,16 * * * /home/ramesh/bin/incremental-backup
# title 1
#    00 – 0th Minute (Top of the hour)
![screenshot](myfile.png?raw=true)
#    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>
* Chrome ''markdown preview plus'' extension does not show images from github.


==== crontab ====
== Markdown editor ==
* crontab SOME-CRON-FILE; crontab -l
* [http://pad.haroopress.com/ Harropad]
* http://linuxbsdos.com/2014/10/05/the-best-markdown-editors-for-linux/


Make sure the .sh file gives a complete path. For example,
= Text editor with navigation =
<pre>
[[Text_editor#Text_editor_with_navigation|Text editor with navigation]]
#!/bin/sh
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>


To disable everything on ''crontab -l'', run ''crontab -e'' then comment out each line you don't want to run with #. OR run ''crontab -r'' to empty the current crontab.
= nano/pico editor =
The nano editor is also called pico in R. See ?edit in R.


==== PATH and Shell ====
[[Text_editor#nano_editor|nano editor]]
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'>
$ cat syncIP
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
</syntaxhighlight>
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.


==== Disable mail alert ====
= vi editor =
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]
[[Text_editor#vi_editor|vi editor]]
<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>


=== Running crontab as root ===
= Cloud =
Use '''sudo crontab -e''' to edit. After saving it, no need to initialize it. Use '''sudo crontab -l''' to list the cron job.
[[Cloud|Cloud]]


=== GUI cron ===
= Boot =
* [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://opensource.com/article/18/1/analyzing-linux-boot-process Analyzing the Linux boot process]
* [https://github.com/alseambusher/crontab-ui Crontab UI]
* [https://utcc.utoronto.ca/~cks/space/blog/linux/LinuxBootOverview? A broad overview of how modern Linux systems boot]
* http://corntab.com/#!


=== md5sum ===
== U-boot ==
[https://www.howtoforge.com/linux-md5sum-command/ Linux md5sum Command Explained For Beginners (5 Examples)]
http://www.denx.de/wiki/U-Boot


How to verify files?
= Pandora linux client =
<pre>
* [http://kevinmehall.net/p/pithos/ Pithos] (GUI)
md5sum file1.txt file2.txt file3.txt > hashes
* [http://6xq.net/projects/pianobar/ Pianobar] (Command line)
md5sum --check hashes
</pre>


=== fsck ===
= COW (copy on write) file system =
[https://www.cyberciti.biz/faq/linux-force-fsck-on-the-next-reboot-or-boot-sequence/ Force fsck on the Next Reboot or Boot Sequence]. Create a blank file ''/forcefsck'' and '''fsck''' will check your drive next time your reboot.
[[Filesystem|filesystem]]
<pre>
sudo touch /forcefsck
</pre>


=== Mount drive ===
= tmpfs and /dev/shm =
==== /etc/fstab and blkid ====
* [https://www.howtoforge.com/storing-files-directories-in-memory-with-tmpfs Storing Files/Directories In Memory With tmpfs]
* https://help.ubuntu.com/community/Fstab
* [https://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html What Is /dev/shm And Its Practical Usage]
** Format: [Device] [Mount Point] [File System Type] [Options] [Dump] [Pass]
* [https://lonesysadmin.net/2013/12/14/use-ram-disk-improve-disk-access-times/ Use a RAM Disk to Improve Disk Access Times]
** <dump> Enable or disable backing up of the device/partition (the command dump). This field is usually set to 0, which disables it.
* [https://kerneltalks.com/linux/how-to-create-ram-disk-in-linux/ How to create RAM disk in Linux]
** <pass> Controls the order in which fsck checks the device/partition for errors at boot time. The root device should be 1. Other partitions should be 2, or 0 to disable checking.
* [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]
** '''man mount'''
* https://wiki.archlinux.org/index.php/Fstab
** Devices that are listed and not present will result in an error unless the '''nofail''' option is used. (good for external devices)
* https://help.ubuntu.com/community/UsingUUID
* [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/
* [https://askubuntu.com/questions/122783/how-do-i-hide-remove-a-partition-from-the-nautilus-left-panel Graphical method using Disks]
* 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
<syntaxhighlight lang='bash'>
$ sudo blkid  #  list devices even not mounted yet
</syntaxhighlight>
and the result should be compared with
<syntaxhighlight lang='bash'>
$ sudo fdisk -l
</syntaxhighlight>
* Run '''sudo 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.
= Apache redirection =
<syntaxhighlight lang='bash'>
http://cran.r-project.org/mirror-howto.html
$ sudo blkid
/dev/sda1: LABEL="WD640" UUID="d3a0a512-bf96-4199-9674-f410f22f0a92" TYPE="ext4"
/dev/sdb1: UUID="afaa4bde-1172-4c54-8b0a-a324ad855355" TYPE="ext4"
/dev/sdb5: UUID="fb2a4ada-d80a-4e23-b4a2-67376b8b7e72" TYPE="swap"


$ sudo fdisk -l
[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]
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
= Important linux directories =
...
[https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html Filesystem Hierarchy Standard], [https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard Wikipedia]
  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
* /bin - executables used by the base system
proc            /proc                                 proc    nodev,noexec,nosuid 0 0
* /boot
UUID=afaa4bde-1172-4c54-8b0a-a324ad855355 /          ext4    errors=remount-ro  0 1
* /dev
UUID=fb2a4ada-d80a-4e23-b4a2-67376b8b7e72 none        swap    sw                  0 0
* /etc - configuration files
/dev/sdb1      /mnt/WD640                            ext4    rw,nosuid,nodev    0 2
* /media
UUID=fb2a4ada-d80a-4e23-b4a2-67376b8b7e70 /mnt/extUSB auto nosuid,nodev,nofail 0 2
* /mnt
* /opt - optional application packages
* /proc - process information only. [https://levelup.gitconnected.com/access-kubernetes-objects-data-from-proc-directory-8d2ec6a0faba Access Kubernetes Objects Data From /Proc Directory]
* /sbin - critical executables for running the system, but should be used by superuser
* /usr - non-critical files. 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)
* /var - variable data such as databases, mails spools and system logs.


$ df -h
= Difference of /bin, /sbin, /usr/local/bin, ... =
Filesystem      Size  Used Avail Use% Mounted on
* '''/bin''' : For essential binaries; e.g. bash, cat, ls.
/dev/sdb1      572G  413G  130G  77% /
* '''/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.
/dev/sdb1      572G  413G  130G  77% /mnt/WD640
* '''/usr/sbin''' : Same as above, but for scripts with superuser (root) privileges required.
</syntaxhighlight>
* '''/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.
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!
<syntaxhighlight lang='bash'>
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1      572G  413G  130G  77% /
...
/dev/sda1      587G  283G  275G  51% /mnt/WD640
</syntaxhighlight>


==== autofs, /etc/auto.master ====
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].
[https://opensource.com/article/18/7/network-attached-storage-Raspberry-Pi Building a network attached storage device with a Raspberry Pi]


==== Fix a malfunctioning USB device or port ====
= DHCP =
[https://www.makeuseof.com/tag/fix-usb-device-port-linux/ 5 Ways to Fix a Malfunctioning USB Device or Port on Linux]


==== USB drive ====
== DHCP server IP ==
* [https://help.ubuntu.com/community/RenameUSBDrive Rename USB drive]
[https://www.cyberciti.biz/faq/linux-find-out-dhcp-server-ip-address/ Linux find DHCP server IP address using CLI]


Run the following to confirm the USB device is detected.
== Get a New IP Address ==
<syntaxhighlight lang='bash'>
{{Pre}}
sudo fdisk -l
dhclient -r  #  release your IP Address
# OR
 
dmesg | grep -i "SCSI"
dhclient  # get your DHCP to issue you a new IP Address based on how it’s been configured.
</syntaxhighlight>
</pre>


Now suppose the usb device is found in '''dev/sdb1'''.
= Open a file/URL using the default application from the command line =
<syntaxhighlight lang='bash'>
* '''gnome-open''' (works on Mint)
sudo mkdir /mnt/usb
* '''kde-open''' (KDE users)
sudo mount -t vfat -o rw,users /dev/sdb1 /mnt/usb
* '''xdg-open''' (window-manager independent). XDG stands for X Desktop Group; see https://en.wikipedia.org/wiki/Freedesktop.org
</syntaxhighlight>
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
<syntaxhighlight lang='bash'>
sudo mount /dev/sdb1 /mnt/usb
</syntaxhighlight>


At the end, run umount command like
See also
<syntaxhighlight lang='bash'>
* [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?]
sudo umount /mnt/usb
* [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]
</syntaxhighlight>


To make the mounting automatically, edit the file '''/etc/fstab'''.
= Check a file's encoding =
<pre>
{{Pre}}
/dev/sdb1      /mnt/usb          vfat    defaults        0      0
file -bi myfile
/dev/sdb1      /mnt/usb          ext3    defaults        0      0
</pre>
</pre>
and run
For example,
<syntaxhighlight lang='bash'>
{{Pre}}
sudo mount -a
file -bi Downloads/hmv_.rc
</syntaxhighlight>
# text/x-c++; charset=utf-16le
 
</pre>
==== Mount an iso file ====
 
* http://www.shellhacks.com/en/Mounting-an-ISO-Image-in-Linux
= Know you system using the command line =
<syntaxhighlight lang='bash'>
* https://www.howtoforge.com/tutorial/get-to-know-your-system/
sudo mkdir -p /mnt/mount_point # create a mount point
sudo mount -o loop /home/user/disk.iso /mnt/mount_point
mount  # verify
</syntaxhighlight>


==== Mount remote Windows share ====
= Alerting and visualization tools =
* http://www.shellhacks.com/en/HowTo-Mount-Remote-Windows-Partition-Share-under-Linux
[https://opensource.com/article/18/10/alerting-and-visualization-tools-sysadmins 5 alerting and visualization tools for sysadmins]


==== Sharing files with Windows by using NitroShare ====
= System monitor tools (TUI) =
[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.


==== exFat - cross platform partition format ====
== glances command: more than htop ==
*[[Mac#ExFat:_Best_drive.2Fpartition_format_to_share_data_between_Mac.2C_Linux_and_OS_X|Mac]]
* 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.
* Gparted cannot create exFAT partition (it is greyed out)
* [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/.
* [http://www.makeuseof.com/tag/exfat-better-different-fat32/ This Trick Makes a USB Drive Work Perfectly With Windows, Mac, Linux, and Anything Else]
** Glances uses online services to grab the external IP address. https://github.com/nicolargo/glances/issues/961
* [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?]
** To hide the internal and external IPs, type "I" (capital).
<syntaxhighlight lang='bash'>
** To disable the IP, type "--disable-ip" (not available in v3.x.x ?)
sudo apt-get install exfat-utils exfat-fuse
** It shows a warning or critical alert (e.g. memory high usage) at the bottom of the screen.
# Still need to create a partition (ex. FAT32) first using gparted in order to get it mounted
** My command: '''glances -t 5'''  # update every 5 seconds
sudo fdisk -l
* https://www.tecmint.com/glances-an-advanced-real-time-system-monitoring-tool-for-linux/
sudo mkfs.exfat -n LABEL /dev/sd**  #  LABEL with whatever you want to label your drive
* [https://youtu.be/E3Ioopzt8ko Monitoring & Troubleshooting Basics with Glances] (video)
</syntaxhighlight>
This should delivery a working exfat file system (read and write support, but not formatting the drives with exfat via Gnome Disks and GParted).


==== NTFS usb drive in xubuntu ====
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'''.
http://xflinux.blogspot.com/2011/01/mount-ntfs-volumes-automatically-in.html
<pre>
sudo apt-get install ntfs-config
</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).
== [https://github.com/brndnmtthws/conky conky] and autostart ==
* [[Ubuntu#Conky|Ubuntu > Conky]] (internal link)
* [[Raspberry#Conky_approach|Raspberry Pi]] case (internal link)


Make sure the " Enable write support for internal devices" option is selected. Now click Close.
For auto start on Lubuntu, see [https://askubuntu.com/a/1148628 How can I add new autostart programs in Lubuntu?]


==== Many drives, one folder ====
On Lubuntu 18.04, add the path to the application to ~/.config/lxsession/Lubuntu/autostart
* [http://www.linuxjournal.com/content/many-drives-one-folder mhddfs] program.


==== Partition tables ====
== '''top''' and '''htop''' command ==
[http://www.makeuseof.com/tag/partition-table-edit-error/ Partition Tables and the Dangers of Editing Them]
* [https://www.binarytides.com/linux-top-command/ 15 simple TOP command examples on Linux to monitor processes]
** 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].


==== parted command ====
== nmon ==
[https://opensource.com/article/18/6/how-partition-disk-linux How to partition a disk in Linux]
* https://en.wikipedia.org/wiki/Nmon. The stats are saved to a comma-separated values (CSV) data file for later graphing and analysis
* [https://www.admin-magazine.com/HPC/Articles/Nmon-All-Purpose-Admin-Tool Monitoring with Nmon]
* [https://javamana.com/2021/11/20211117161849527S.html Linux系统性能监控工具nmon]


==== Recommended partition schemes ====
== CPU frequency ==
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s2-diskpartrecommend-x86.html Redhat]
[https://unix.stackexchange.com/a/265611 What is the correct way to view your CPU speed on Linux?] (x86)
* [https://www.debian.org/releases/stable/i386/apcs03.html.en Debian]
<pre>
* [https://help.ubuntu.com/community/PartitioningSchemes Ubuntu]
watch -n.1 "cat /proc/cpuinfo | grep \"^[c]pu MHz\""
* [https://www.centos.org/docs/5/html/5.2/Installation_Guide/s2-diskpartrecommend-s390.html CentOS]
</pre>
* [https://wiki.archlinux.org/index.php/partitioning#Discrete_partitions Arch] Linux


==== Why put things other than /home to a separate partition? ====
[https://unix.stackexchange.com/a/590531 How can I get the current CPU frequency of an ARM processor on Ubuntu?]
[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?]
<pre>
ls /sys/devices/system/cpu/cpu0/cpufreq/
</pre>


The /var partition is used by Docker and Apache.
== [https://scoutapp.github.io/scout_realtime/ scout_realtimep] ==
This is used by [https://docs.dataplicity.com/docs/remotely-monitor-your-pi Dataplicity]


[https://unix.stackexchange.com/a/84764 /home, /boot and /var partitions] can be separated.
== [https://github.com/aksakalli/gtop gtop] command (100% Javascript) ==
https://www.cyberciti.biz/howto/gtop-awesome-system-monitoring-dashboard-for-terminal/.  


=== How do I send an already-running process into the background ===
Pros:
* http://stackoverflow.com/questions/625409/how-do-i-put-an-already-running-process-under-nohup
* CPU history graph in time
* [https://www.cyberciti.biz/faq/unix-linux-bg-command-examples-usage-syntax/ bg Command Examples]
* 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


Steps:
{{Pre}}
# 'Ctrl+Z' to stop (pause) the program and get back to the shell.
$ docker run --rm -it \
# '''bg''' to run it in the background.
    --name gtop \
# '''jobs -l''' to get the jobID and process ID
    --net="host" \
# '''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.
    --pid="host" \
    aksakalli/gtop


==== Stopped job ====
$ sudo apt install npm nodejs
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.
$ npm install gtop -g
$ gtop
</pre>


* '''jobs -s''' showing stopped jobs
* Press p to sort by process ID (PID).
* '''jobs -l''' showing the job PID
* Press c to sort by CPU usage.
* Press m to sort by memory usage.


[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.
It can be installed on Linux Mint 18.2 but not in Ubuntu 14.04 or raspbian (9 stretch).
* '''fg %1''' move the stopped job ID #1 to the foreground (works)
<pre>
* '''kill %1''' # kill job ID #1
$ npm install gtop -g
* '''kill 12345''' # kill job PID 12345
npm http GET https://registry.npmjs.org/gtop
* '''kill -9 `jobs -ps`''' may not work
npm http GET https://registry.npmjs.org/gtop
* '''kill -9 $(jobs -p)'''


=== run commands in a background and allow log off ===
npm http GET https://registry.npmjs.org/gtop
<syntaxhighlight lang='bash'>
npm ERR! Error: CERT_UNTRUSTED
nohup /path/to/script >output 2>&1 &
npm ERR!    at SecurePair.<anonymous> (tls.js:1370:32)
</syntaxhighlight>
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]>


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.
npm ERR! System Linux 4.4.0-119-generic
<syntaxhighlight lang='bash'>
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "gtop" "-g"
nohup command </dev/null >/dev/null 2>&1 &
npm ERR! node -v v0.10.25
</syntaxhighlight>
npm ERR! npm -v 1.3.10
</pre>


See also [https://en.wikipedia.org/wiki/Process_substitution#Anonymous_named_pipe Anonymous named pipe].
== [https://github.com/cjbassi/gotop gotop] ==
A terminal based graphical activity monitor inspired by gtop and vtop. It is quite beautiful.


=== Notepadqq - Notepad++-like editor ===
[https://www.ostechnix.com/gotop-yet-another-tui-graphical-activity-monitor-written-in-go/ Gotop – Yet Another TUI Graphical Activity Monitor, Written In Go]
[http://www.ubuntugeek.com/notepadqq-the-linux-source-editor.html Notepadqq]. It is written using Qt. It does not have printing function:(


=== Note apps that can sync ===
Compared to gtop, it has a temperature monitor. However, it can only show the average CPU usage (one line) on my Xeon computer.
[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.


=== Evernote ===
{{Pre}}
==== Evernote alternative ====
git clone --depth 1 https://github.com/cjbassi/gotop /tmp/gotop
[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]
/tmp/gotop/scripts/download.sh
 
sudo cp gotop /usr/local/bin; rm gotop
==== Backup/restore Evernote ====
gotop
https://www.makeuseof.com/tag/backup-restore-evernote/
 
=== 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. 
<syntaxhighlight lang='bash'>
sudo pip install grip
grip readme.md
</syntaxhighlight>
* 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>
</pre>
* Chrome ''markdown preview plus'' extension does not show images from github.
Note the temperatures do not show up in Raspbian (raspberry pi 3 b+).


==== Markdown editor ====
=== termui: Golang terminal dashboard ===
* [http://pad.haroopress.com/ Harropad]
https://github.com/gizak/termui
* http://linuxbsdos.com/2014/10/05/the-best-markdown-editors-for-linux/


=== Text editor with navigation ===
=== Bashtop and btop ===
[[Text_editor#Text_editor_with_navigation|Text editor with navigation]]
* [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].


=== nano/pico editor ===
== S-tui command ==
The nano editor is also called pico in R. See ?edit in R.
[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]


[[Text_editor#nano_editor|nano editor]]
== below ==
[https://fedoramagazine.org/below-a-time-traveling-resource-monitor/ below: a time traveling resource monitor]


=== vi editor ===
= System monitor tools (GUI) =
[[Text_editor#vi_editor|vi editor]]


=== Cloud ===
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


http://slidedecks.wilmoore.com/2012-confoo/diy-private-cloud-using-virtualBox-and-chef/#66
Some lists:
* [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]


http://www.datacentermap.com/blog/cloud-software-389.html
== Linux-Dash ==
https://github.com/afaqurk/linux-dash. Not working when I tested on RPi and Ubuntu.


* [http://www.openstack.org/ OpenStack]:Open source software for building private and public clouds. Great for large infrastructures. Cf: Amazon Elastic Compute Cloud (EC2).
== Nagios ==
** http://www.tikalk.com/alm/blog/expreimenting-openstack-essex-ubuntu-1204-lts-under-virtualbox
* [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]
** http://www.ibm.com/developerworks/cloud/library/cl-openstack-cloud/
* [https://en.wikipedia.org/wiki/Icinga Icinga] (Nagios fork)
* [http://incubator.apache.org/cloudstack/ CloudStack]
** [http://www.ubuntugeek.com/how-to-install-icinga-nagios-fork-in-ubuntu-12-10-server.html icinga]
* [http://www.eucalyptus.com/ Eucalyptus] API compatible with Amazon EC2
** [https://www.howtoforge.com/tutorial/how-to-install-icinga2-on-debian-9/ How to Install Icinga 2 Monitoring Tool on Debian 9.2]
* [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].
** [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]


Commercial cloud services
== [https://www.zabbix.com/ Zabbix] ==
* [https://www.digitalocean.com/ DigitalOcean] - simple pricing. One droplet = one server.
* [https://www.tecmint.com/install-zabbix-on-debian-10/ How to Install Zabbix on Debian 10]
* Amazon EC2
* [https://forum.proxmox.com/threads/smart-error-health-detected-on-host.109580/ SMART error (Health) detected on host]
* Google cloud
* [https://www.zabbix.com/integrations/smart Zabbix + S.M.A.R.T.]
* Microsoft Azure


==== Manage all your cloud storage ====
== Munin and Monit ==
http://www.makeuseof.com/tag/chrome-extensions-you-need-manage-cloud-storage/
[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


==== Dropbox ====
== [https://www.cacti.net/ Cacti] ==
[https://www.ostechnix.com/dbxfs-mount-dropbox-folder-locally-as-virtual-file-system-in-linux/ Dbxfs – Mount Dropbox Folder Locally As Virtual File System In Linux]. It is a command line dropbox client and requires no disk space for access.
* http://terraltech.com/monitoring-with-cacti/
* https://www.howtoforge.com/tutorial/install-cacti-on-debian-9/


==== Comparison of Linux VPS providers ====
== [https://github.com/sysstat/sysstat sysstat], sar ==
https://www.ghacks.net/2017/06/15/a-comparison-of-linux-vps-providers-for-beginner-hosting/
{{Pre}}
# CPU
sar 2 10 # every two seconds, 10 times
# Memory
sar -r  # look at the kbcommit and commit columns


=== Boot ===
sar -r -f /var/log/sysstat/sa02
* [https://opensource.com/article/18/1/analyzing-linux-boot-process Analyzing the Linux boot process]
</pre>
* [https://utcc.utoronto.ca/~cks/space/blog/linux/LinuxBootOverview? A broad overview of how modern Linux systems boot]
* 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).


==== U-boot ====
== Stacer ==
http://www.denx.de/wiki/U-Boot
[[Ubuntu#Stacer_-_Linux_System_Optimizer_and_Monitoring|Linux System Optimizer and Monitoring]]


=== Pandora linux client ===
== Prometheus ==
* [http://kevinmehall.net/p/pithos/ Pithos] (GUI)
* https://prometheus.io/docs/introduction/overview/
* [http://6xq.net/projects/pianobar/ Pianobar] (Command line)
* [https://www.howtoforge.com/how-to-install-prometheus-system-monitoring-tool-on-debian-11/ How to Install Prometheus System Monitoring Tool on Debian 11]


=== COW (copy on write) file system ===
= [https://en.wikipedia.org/wiki/Curses_%28programming_library%29 Curses] and [https://en.wikipedia.org/wiki/Ncurses ncurses]: TUI library =
The cow filesystem was found on xubuntu live CD. See http://en.wikipedia.org/wiki/Copy-on-write


[https://www.digitalocean.com/community/tutorials/how-to-protect-your-server-against-the-dirty-cow-linux-vulnerability How To Protect Your Server Against the Dirty COW Linux Vulnerability] (10/21/2016)
[https://opensource.com/article/21/8/ncurses-linux Position text on your screen in Linux with ncurses]


=== Apache redirection ===
== Calcurse ==
http://cran.r-project.org/mirror-howto.html
[https://opensource.com/article/18/10/calcurse Keep up with your calendar and to-do list with Calcurse]


[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]
= Bitbucket (free for 5 users) =
[https://confluence.atlassian.com/display/BITBUCKET/Bitbucket+101  Bitbucket 101]


=== Important linux directories ===
* Unlimited private repos
* /bin - executables used by the base system
* Code reviews
* /boot
* JIRA integration
* /dev
* REST API
* /etc - configuration files
* Custom domains
* /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, ... ===
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.
* /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.  


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].
See [http://blog.bitbucket.org/2011/12/21/mobile-apps-for-bitbucket/ here] for a list of Android apps related to bitbucket.


=== DHCP lease time ===
= Image =
See [[Images|Images]].


On Windows, it is 8 days.
= [https://www.gimp.org/ GIMP] =


==== Get a New IP Address ====
= Reload/Refresh .profile file =
<syntaxhighlight lang='bash'>
https://askubuntu.com/a/59127
dhclient -r  #  release your IP Address
<pre>
. ~/.profile
</pre>
<span style="border: 1px solid black">'''.'''</span> is a '''bash''' builtin and a synonym for source, see man bash.


dhclient  #  get your DHCP to issue you a new IP Address based on how it’s been configured.
[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.]
</syntaxhighlight>


=== Open a file/URL using the default application from the command line ===
= History of commands =
* '''gnome-open''' (works on Mint)
* [http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/ 15 Examples To Master Linux Command Line History]
* '''kde-open''' (KDE users)
* [https://www.networkworld.com/article/3537214/tweaking-history-on-linux.html Tweaking history on Linux]
* '''xdg-open''' (window-manager independent). XDG stands for X Desktop Group; see https://en.wikipedia.org/wiki/Freedesktop.org


See also
== history command with date and time ==
* [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?]
* http://www.cyberciti.biz/faq/unix-linux-bash-history-display-date-time/
* [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]


=== Check a file's encoding ===
Running the following code once and history will give date and time the next time you issue the '''history''' command.
<syntaxhighlight lang='bash'>
<pre>
file -bi myfile
echo 'export HISTTIMEFORMAT="%Y-%m-%d %T "' >> ~/.bashrc
</syntaxhighlight>
</pre>
For example,
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].
<syntaxhighlight lang='bash'>
file -bi Downloads/hmv_.rc
# text/x-c++; charset=utf-16le
</syntaxhighlight>


=== Know you system using the command line ===
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.
* https://www.howtoforge.com/tutorial/get-to-know-your-system/


=== Alerting and visualization tools ===
== Bang bang - Run a command/Fetch parameters from previous ''history'' ==
[https://opensource.com/article/18/10/alerting-and-visualization-tools-sysadmins 5 alerting and visualization tools for sysadmins]
* http://unixhelp.ed.ac.uk/shell/tcsh_hist3.html
* http://codytaylor.org/2009/09/linux-bang-commands.html


=== System monitor tools (TUI) ===
# ^P: Move up through the command history list one command at a time.
==== [https://github.com/brndnmtthws/conky conky] ====
# ^N: Move down through the command history list one command at a time.
* [[Ubuntu#Conky|Ubuntu > Conky]] (internal link)
# '''!!''': Run the previous command. For example, we can run '''sudo !!''' in order to run the previous command with sudo.
* [[Raspberry#Conky_approach|Raspberry Pi]] case (internal link)
# '''!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.


==== '''htop''' command ====
For example,
* [http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages Understand Linux CPU Load]
<pre>
!-1
!4
!tail
</pre>


==== glances command ====
== Recall commands with reverse-i-search ==
* https://nicolargo.github.io/glances/ and its [http://glances.readthedocs.io/en/latest/ Documentation]
Ctrl + r. See [https://www.redhat.com/sysadmin/bash-bang-commands Bash bang commands: A must-know trick for the Linux command line]
* [http://www.ubuntugeek.com/install-glances-on-ubuntu-16-04.html Glances] includes disk i/o, network too. Its official website at http://glances.readthedocs.io/en/latest/.
* https://www.tecmint.com/glances-an-advanced-real-time-system-monitoring-tool-for-linux/


Glances is similar to htop but it provides network stats too. Install it by '''sudo apt-get install glances'''.
To continue with the search, just hit Ctrl + r keys again.


==== [https://scoutapp.github.io/scout_realtime/ scout_realtimep] ====
To run a forward search, hit Ctrl + s. [https://unix.stackexchange.com/a/73499 How to cycle through reverse-i-search in BASH?]
This is used by [https://docs.dataplicity.com/docs/remotely-monitor-your-pi Dataplicity]


==== [https://github.com/aksakalli/gtop gtop] command (100% Javascript) ====
== Increase history limit ==
https://www.cyberciti.biz/howto/gtop-awesome-system-monitoring-dashboard-for-terminal/.  
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>
$ echo $HISTSIZE  # $HISTSIZE variable controls how much history is displayed
500
$ export HISTSIZE=1000
$ echo “HISTSIZE=1000” >> ~/.bashrc


Pros:
# $HISTFILESIZE variable controls how many commands are retained in your .bash_history file.
* CPU history graph in time
$ echo $HISTFILESIZE
* Memory history graph in time (not useful)
2000
* Network bandwidth usage is real-time. It is accurate as what [[#nload|nload]] gives.
$ wc -l .bash_history
* Percentage usage of memory, swap, disk usage
2000 .bash_history
* Top processes
</pre>


<syntaxhighlight lang='bash'>
== Not to add to bash history ==
$ sudo apt install npm nodejs
[https://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_or_Ubuntu#Configure_MySQL Add a space after the command].
$ npm install gtop -g
$ gtop
</syntaxhighlight>


* Press p to sort by process ID (PID).
It is useful if there is a password in the command.
* 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).
For example,
<pre>
<pre>
$ npm install gtop -g
$ ls ~/            # this won't be recorded in history
npm http GET https://registry.npmjs.org/gtop
$  ls ~/Downloads/  # this will be recorded in history
npm http GET https://registry.npmjs.org/gtop
$ history
</pre>
 
== Delete a single command from history ==
* [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]


npm http GET https://registry.npmjs.org/gtop
To stop adding history entries, you can place a space before the command, as long as you have '''ignorespace''' in your '''HISTCONTROL''' environment variable.
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>


npm ERR! System Linux 4.4.0-119-generic
You can force Bash to exclude commands starting with empty space by placing this in your .bashrc file:
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "gtop" "-g"
<pre>
npm ERR! node -v v0.10.25
export HISTCONTROL=$HISTCONTROL:ignorespace
npm ERR! npm -v 1.3.10
</pre>
</pre>


==== [https://github.com/cjbassi/gotop gotop] ====
== [https://www.howtoforge.com/clear-bash-history/ How to Clear Bash History on Linux] ==
A terminal based graphical activity monitor inspired by gtop and vtop. It is quite beautiful.
{{Pre}}
$ cat /dev/null > ~/.bash_history && history -c && exit
</pre>


[https://www.ostechnix.com/gotop-yet-another-tui-graphical-activity-monitor-written-in-go/ Gotop – Yet Another TUI Graphical Activity Monitor, Written In Go]
== 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].


Compared to gtop, it has a temperature monitor. However, it can only show the average CPU usage (one line) on my Xeon computer.
= Listen to HiChannel internet radio =
Use [http://radiotray.sourceforge.net/ Radio Tray]


<syntaxhighlight lang='bash'>
* http://endroid.blogspot.com/2012/02/listen-hichannel-radio-online-by.html
git clone --depth 1 https://github.com/cjbassi/gotop /tmp/gotop
* http://abcde9990101.blogspot.com/2011/05/ubunturadio-tray.html
/tmp/gotop/scripts/download.sh
sudo cp gotop /usr/local/bin; rm gotop
gotop
</syntaxhighlight>
Note the temperatures do not show up in Raspbian (raspberry pi 3 b+).


==== S-tui command ====
I use it to listen m3u file (VLC also supports it too).
[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]


=== System monitor tools (GUI) ===
= [http://en.wikipedia.org/wiki/Web_analytics Web Analytics Reporting Tools] =
Comparisons:
* [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]
* https://www.tecmint.com/linux-performance-monitoring-tools/  
* [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]
* https://linoxide.com/monitoring-2/linux-performance-monitoring-tools/
* [http://awstats.sourceforge.net/ AWStats]
* http://www.linuxscrew.com/2012/03/22/linux-monitoring-tools/
* [http://www.google.com/analytics/ Google Analytics]
* https://www.infoworld.com/article/2683857/network-monitoring/article.html#slide2
* http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools


Some lists:
= Painting software =
* [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://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].  
* [https://en.wikipedia.org/wiki/Icinga Icinga] (Nagios fork)
<ul>
** [http://www.ubuntugeek.com/how-to-install-icinga-nagios-fork-in-ubuntu-12-10-server.html icinga]
<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!]
** [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]
* [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
* [https://www.cacti.net/ Cacti]
** http://terraltech.com/monitoring-with-cacti/
** https://www.howtoforge.com/tutorial/install-cacti-on-debian-9/
* [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]
* [https://github.com/sysstat/sysstat sysstat] & the '''sar''' command
** 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).
<pre>
<pre>
# CPU
sudo add-apt-repository ppa:pinta-maintainers/pinta-stable
sar 2 10 # every two seconds, 10 times
sudo apt update
# Memory
sudo apt install pinta
sar -r  # look at the kbcommit and commit columns
 
sar -r -f /var/log/sysstat/sa02
</pre>
</pre>
</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]


=== [https://en.wikipedia.org/wiki/Curses_%28programming_library%29 Curses] and [https://en.wikipedia.org/wiki/Ncurses ncurses]: TUI library ===
== Take a screenshot (and edit them) ==
==== Calcurse ====
See [[#Take_screenshots_.28and_edit_them.29|Take screenshots]].
[https://opensource.com/article/18/10/calcurse Keep up with your calendar and to-do list with Calcurse]


=== Bitbucket (free for 5 users) ===
= [https://cozy.geigi.de/ Cozy] - audiobook player =
[https://confluence.atlassian.com/display/BITBUCKET/Bitbucket+101  Bitbucket 101]
* [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]


* Unlimited private repos
= ebook readers =
* Code reviews
[https://itsfoss.com/best-ebook-readers-linux 7 Best eBook Readers for Linux]: Calibre, FBReader, Okular, Lucidor, Bookworm, Easy Ebook Viewer and Buka.
* JIRA integration
* REST API
* Custom domains


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.
== [http://calibre-ebook.com/download_linux Calibre] - Read ebook in epub format ==
See [[Calibre|Calibre]]


See [http://blog.bitbucket.org/2011/12/21/mobile-apps-for-bitbucket/ here] for a list of Android apps related to bitbucket.
= RSS reader =
Some references:
# [https://itsfoss.com/feed-reader-apps-linux/ 5 Best Feed Reader Apps for Linux]
# [https://www.tecmint.com/best-rss-feed-readers-for-linux/ 14 Best RSS Feed Readers for Linux in 2018]. It contains nice screenshots.


=== Image ===
Some examples:
[https://opensource.com/article/17/8/imagemagick English original], [https://linux.cn/article-8851-1.html ImageMagick 入门:使用命令行来编辑图片]
* [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.


==== Convert a color image to black and white ====
= Clear gibberish all over the screen =
* https://linux.cn/article-8851-1.html
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.
* https://www.imagemagick.org/script/command-line-options.php#canny


<pre>
= Display/screen =
$ convert filename.jpg -canny 0x1 -negate canny.jpg
== Turn off/on your monitor via command line ==
convert.im6: unrecognized option `-canny' @ error/convert.c/ConvertImageCommand/1107.
* 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
$ convert --version
{{Pre}}
Version: ImageMagick 6.7.7-10 2017-07-31 Q16 http://www.imagemagick.org
xset dpms force off # Press any key to turn it on
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
xset dpms force on
Features: OpenMP 
xset -q # check the status of the X server settings
</pre>
</pre>


[https://www.imagemagick.org/script/download.php The current imagemagick version] is 7.0.7-15.
If we want to turn off/on the screen via ssh, add
 
{{Pre}}
==== Install/build the latest imagemagick ====
export DISPLAY=:0.0
* https://www.imagemagick.org/script/install-source.php
</pre>
* https://gist.github.com/makenova/78bb63aaa1050e2ad8019ee1e7e7b433
first before calling the '''xset''' command, or use '-display' argument
* https://www.tutorialspoint.com/articles/how-to-install-imagemagick-on-ubuntu
{{Pre}}
xset -display :0.0 dpms force off
xset -display :0.0 dpms force on
</pre>


<syntaxhighlight lang='bash'>
== autoxrandr ==
# remove version installed with apt-get
Plug your laptop into different monitor setups. https://www.donarmstrong.com/posts/autorandr/
sudo apt-get remove imagemagick && sudo apt-get autoremove


# install dependencies
== Move a window without clicking the titlebar ==
sudo apt-get install build-essential
Hold down the '''Alt''' key and then click in the window anywhere, and move your mouse.
sudo apt-get build-dep imagemagick -y


# download ImageMagick source
== Add new screen/display resolutions ==
wget http://www.imagemagick.org/download/ImageMagick.tar.gz
* 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
tar xzvf ImageMagick.tar.gz
{{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>


# build source
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.
cd ImageMagick-*
./configure
make


# install and verify
== Wayland ==
sudo make install
* '''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>


sudo checkinstall
== export DISPLAY ==
<ul>
<li>[https://askubuntu.com/a/432257 What is the $DISPLAY environment variable?]
The value of the display environment variable is:
<pre>
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>
</ul>


**********************************************************************
= See which groups you belong to, id & group commands =
* [https://www.2daygeek.com/how-to-check-which-groups-a-user-belongs-to-on-linux/ How To Check Which Groups A User Belongs To On Linux]
* [https://www.2daygeek.com/find-check-user-name-and-other-information-in-linux/ 6 Simple ways to check Username and related information in Linux]
<pre>
id <username>
groups
groups <username>
</pre>


Done. The new package has been installed and saved to
== Main Types of User Accounts on Linux ==
[https://www.makeuseof.com/types-of-user-accounts-on-linux/ The 4 Main Types of User Accounts on Linux]


/home/XXX/Downloads/ImageMagick-7.0.7-15/imagemagick-7.0.7_15-1_amd64.deb
== finger: show user information ==
finger USERNAME


You can remove it from your system anytime using:  
== List all user groups ==
[https://www.makeuseof.com/how-to-list-all-user-groups-on-linux/ How to List All User Groups on Linux]


      dpkg -r imagemagick-7.0.7
= groupadd, chgrp, usermod, ACL (access control lists) =
* [https://www.cyberciti.biz/faq/howto-linux-add-user-to-group/ Linux Add User To Group Using Command-Line]: '''useradd'''
* [http://www.tecmint.com/create-a-shared-directory-in-linux/ Create a Shared Directory for All Users in Linux]
* [https://www.tecmint.com/give-read-write-access-to-directory-in-linux/ Assign Read/Write Access to a User on Specific Directory in Linux]
* [https://www.howtoforge.com/linux-chgrp-command/ Linux Chgrp Command for Beginners (5 Examples)]


**********************************************************************
{{Pre}}
sudo mkdir -p /var/www/reports/
sudo groupadd project


$ convert --version
sudo usermod -a -G project tecmint
# bash: /usr/bin/convert: No such file or directory
sudo chgrp -R project /var/www/reports/
 
sudo chmod -R 2775 /var/www/reports/
$ which convert
</pre>
/usr/local/bin/convert
$ whereis convert
convert: /usr/local/bin/convert
$ /usr/local/bin/convert -version
Version: ImageMagick 7.0.7-15 Q16 x86_64 2017-12-20 http://www.imagemagick.org
Copyright: © 1999-2018 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP
Delegates (built-in): bzlib fontconfig freetype jbig jng jpeg lzma pangocairo png tiff x xml zlib
</syntaxhighlight>


==== Convert an image to sketch (online tool) ====
create more system users and add them to the directory group as follows:
http://www.snapstouch.com/sketch.aspx
{{Pre}}
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


==== Convert an image file to a different format (eg icon) ====
sudo mkdir -p /var/www/reports/aaron_reports
Using the [http://www.imagemagick.org/script/index.php imagemagic] program.
sudo mkdir -p /var/www/reports/john_reports
<syntaxhighlight lang='bash'>
sudo mkdir -p /var/www/reports/ravi_reports
convert winamp-ncrow.png -resize 32x32 winamp-ncrow.ico
</pre>
</syntaxhighlight>


[http://www.tecmint.com/linux-image-conversion-tools/ 4 Ways to Batch Convert Your PNG to JPG and Vice-Versa]
== See who's in a group ==
<pre>
grep '^group_name_here:' /etc/group


==== Rotate an image ====
finger USERNAME # See more detail about a user
http://www.imagemagick.org/script/command-line-options.php#rotate
</pre>
<syntaxhighlight lang='bash'>
convert winamp-ncrow.png -rotate 45 winamp-ncrow2.png  # 45 degrees
</syntaxhighlight>


One problem with this simple approach is the picture size (not image file) changed (become smaller) if the degree is not one of 90,180 or 270.
== Add a standard user to '''sudo''' group ==
==== Create an animated gif file ====
This is useful on Debian distribution where a new user does not have the sudo power. First log in as root,
Use the script [http://www.imagemagick.org/Usage/warping/animate_distort_rot here]. See the last example on [http://www.imagemagick.org/Usage/warping/#animations here]. The rotation speed looks good too! Just change the source image file in the script.
{{Pre}}
<syntaxhighlight lang='bash'>
# usermod -aG sudo username
#!/bin/sh
</pre>
#
# Create a rotating figure using Distort SRT transformations
#
command='convert -delay 10 koala.gif -virtual-pixel white'


for i in `seq 5 5 360`; do
= Shared library management =
  command="$command \\( -clone 0 -distort SRT $i \\)"
http://www.cyberciti.biz/tips/linux-shared-library-management.html
done


command="$command -delete 0 -loop 0 animate_distort_rot.gif"
# 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.


eval $command
= 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>


chmod 644 animate_distort_rot.gif
== ssh log files: '''/var/log/auth.log''' ==
</syntaxhighlight>
* /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''.


[http://askubuntu.com/questions/43763/tool-to-convert-a-sequence-of-numbered-png-files-to-an-animated-gif?noredirect=1&lq=1 Tool to convert a sequence of numbered PNG files to an animated GIF?]. [https://www.imagemagick.org/script/convert.php Convert command line option]. The option '-loop 0' means repeats infinitely and '-delay 200' means 2 seconds delay between each frame.
And
<syntaxhighlight lang='bash'>
* [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?]
convert -delay 200 -loop 0 file_1.png file_2.png file_3.png animated.gif
* [https://ubuntuforums.org/showthread.php?t=1256801 remove cron from /var/log/auth.log]
</syntaxhighlight>
* [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)]


==== Edit gif file ====
== lnav (The Logfile Navigator) ==
[https://www.maketecheasier.com/create-gifs-command-tool-ubuntu/ gifsicle] package
[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'''


==== Replace transparency in PNG images with white background ====
== Apache log ==
http://stackoverflow.com/questions/2322750/replace-transparency-in-png-images-with-white-background
* /var/log/apache2/error.log (small 83K). Useful to troubleshoot errors/crashes of Apache.
<syntaxhighlight lang='bash'>
<pre>
convert image.png -background white -alpha remove white.png
grep "May 08" /var/log/apache2/error.log
</syntaxhighlight>
</pre>  
 
* /var/log/apache2/access.log (large 10M)
==== Remove GPS metadata from jpg files - [http://www.sno.phy.queensu.ca/~phil/exiftool/ exiftool]====
<syntaxhighlight lang='bash'>
sudo apt-get install libimage-exiftool-perl
exiftool -gps:all= -xmp:geotag= image.jpg
</syntaxhighlight>
The image file will be updated. To check the current metadata, use
<syntaxhighlight lang='bash'>
exiftool image.jpg
</syntaxhighlight>


Note that the above command only remove gps information. The other information like date/time of creation, camera model are not changed.
== mail ==
/var/log/maillog


Exitftool can also be used to edit the [https://askubuntu.com/questions/27381/how-to-edit-pdf-metadata-from-command-line metadata on PDF files].
== Logrotate ==
<syntaxhighlight lang='bash'>
[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)]
exiftool -Title="This is the Title" -Author="Happy Man" -Subject="PDF Metadata" drawing.pdf
</syntaxhighlight>


==== Edit Svg image ====
= uprecords command =
* [https://inkscape.org/en/ Inkscape]
* [https://linuxtldr.com/uprecords-command/ Check the Linux Uptime History Using the Uprecords]
* Inkscape from [https://fedoramagazine.org/ Fedora magazine]
* [https://linuxhandbook.com/uptime-command/ How to Check Uptime of Your Linux Server]
** [https://fedoramagazine.org/getting-started-inkscape-fedora/ Getting started with Inkscape on Fedora]
** [https://fedoramagazine.org/inkscape-adding-colour/ Inkscape: Adding some colour]
** [https://fedoramagazine.org/inkscape-design-imagination/ Create a simple wallpaper with Fedora and Inkscape]


==== Animated gif ====
= '''uptime''' command =
* [https://www.howtoforge.com/tutorial/how-to-generate-a-animated-gif-or-movie-out-of-images-on-linux/#using-photofilmstrip How to generate a animated GIF or movie out of images on Linux] (GIMP or PhotoFilmStrip)
{{Pre}}
* [http://superuser.com/questions/558790/how-do-i-convert-gif-to-png-this-image-to-get-the-original-view convert (.gif to .png) this image to get the original view?] (ImageMagick)
uptime
watch -n 60 uptime
</pre>


==== Display images in the terminal ====
Windows
[https://www.ostechnix.com/how-to-display-images-in-the-terminal/ Using FIM]
* [https://www.windowscentral.com/how-check-your-computer-uptime-windows-10#check_pc_uptime_cmd How to check PC uptime using Command Prompt]
* [https://www.bettertechtips.com/windows/check-uptime-windows-10/ 4 Ways to Check the System Uptime in Windows 10]
* [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]


=== [https://www.gimp.org/ GIMP] ===
== 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?]


=== login shell (.bash_profile) vs interactive shell (.bashrc) ===
== Get notified when a system is rebooted ==
* http://stackoverflow.com/questions/18186929/differences-between-login-shell-and-interactive-shell
[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]].
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.
= '''timeout''' command =
# '''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.
* https://www.howtoforge.com/linux-timeout-command/
export environment variables
* https://www.howtogeek.com/423286/how-to-use-the-timeout-command-on-linux/
# 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 ===
= Linux command similar to ''top'' to show hard disk activity =
* [http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/ 15 Examples To Master Linux Command Line History]
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.
{{Pre}}
sudo apt-get install iotop


==== history command with date and time ====
sudo iotop -o -u $USER
* http://www.cyberciti.biz/faq/unix-linux-bash-history-display-date-time/
</pre>


Running the following code once and history will give date and time the next time you issue the '''history''' command.
Another program is '''iostat''' and the '''-d''' (disk) option. The '''-x''' option will display extension I/O status.
<pre>
<pre>
echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc
sudo apt-get install sysstat
iostat -dx 5 # every 5 seconds
</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].
[http://www.thegeekstuff.com/2011/07/iostat-vmstat-mpstat-examples/ 24 iostat, vmstat and mpstat Examples for Linux Performance Monitoring]
 
= curl and wget =
See [[Curl|Curl]].


==== Bang bang - Run a command/Fetch parameters from previous history ====
= Torrent =
* http://unixhelp.ed.ac.uk/shell/tcsh_hist3.html
== [https://github.com/kryptxy/torrench Torrench] ==
* http://codytaylor.org/2009/09/linux-bang-commands.html
[https://fossbytes.com/review-torrench-download-torrents-using-terminal-linux/ Torrench: How To Search And Download Torrent Files Using Terminal (Linux, Mac, Windows)]
* http://craig-russell.co.uk/2011/09/28/bang-bang-command-recall-in-linux.html#.VHXnq3Wx3UY
* http://requiremind.com/linux-command-line-tips-become-a-master/


# ^P: Move up through the command history list one command at a time.
== aria2 - command line downloader supports torrents and multi-connection ==
# ^N: Move down through the command history list one command at a time.
[http://www.2daygeek.com/aria2-command-line-download-utility-tool/ aria2 command examples]
# !!: 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,
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+ */ " >
!-1
$ time aria2c  http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 16 seconds
!4
$ time aria2c -x10 http://mirror.jmu.edu/pub/archlinux/iso/2016.11.01/archlinux-bootstrap-2016.11.01-i686.tar.gz # 11 seconds
!tail
</pre>
</pre>


==== Increase history limit ====
= Axel =
http://unix.stackexchange.com/questions/17574/is-there-a-maximum-size-to-the-bash-history-file
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/
 
= [http://lftp.yar.ru/ lftp] =
* [http://www.linuxquestions.org/questions/linux-software-2/command-line-ftp-client-94510/ It supports FXP (site-to-site transfers) and dropping to background]
* [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.


==== Not to add to bash history ====
= Apply a patch to source code =
[https://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_or_Ubuntu#Configure_MySQL Add a space after the command].
* 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]


==== [https://www.howtoforge.com/clear-bash-history/ How to Clear Bash History on Linux] ====
For example [https://groups.google.com/forum/#!topic/tuxedo-tools-users/BVNDDmInU0A Tophat 2.0.12 compatibility with Samtools 1.0],
<syntaxhighlight lang='bash'>
{{Pre}}
$ cat /dev/null > ~/.bash_history && history -c && exit
$ ls
</syntaxhighlight>
support_for_tophat_1.patch  tophat-2.0.12  tophat-2.0.12.tar.gz


=== Listen to HiChannel internet radio ===
$ grep -r -i "check_samtools" tophat-2.0.12/
Use [http://radiotray.sourceforge.net/ Radio Tray]
tophat-2.0.12/src/tophat.py:def check_samtools():
tophat-2.0.12/src/tophat.py:        check_samtools()


* http://endroid.blogspot.com/2012/02/listen-hichannel-radio-online-by.html
$ cp support_for_tophat_1.patch tophat-2.0.12/src/
* http://abcde9990101.blogspot.com/2011/05/ubunturadio-tray.html
$ 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).
</pre>


I use it to listen m3u file (VLC also supports it too).
= IP address fundamental =
http://www.howtogeek.com/133943/geek-school-learning-windows-7-ip-addressing-fundamentals/.  


=== [http://en.wikipedia.org/wiki/Web_analytics Web Analytics Reporting Tools] ===
There are three classes for private IP ranges.
* [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]
* 1-126.0.0.0 from Class A
* [http://awstats.sourceforge.net/ AWStats]
* 128-191.0.0.0 from Class B
* [http://www.google.com/analytics/ Google Analytics]
* 192-223.0.0.0 from Class C


=== Painting software ===
[[#Subnet|Subnet]]
* [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].
 
* [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 (1st one) on the left hand side, then select a rectangle. Now click 'Image' > 'Crop to Selection' to finish.
= Gateway IP address =
* [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.
[https://ostechnix.com/find-default-gateway-linux/ How To Find Default Gateway IP Address In Linux And Unix From Commandline]
* [http://www.ubuntugeek.com/install-mypaint-on-ubuntu-15-10.html MyPaint]
 
= Get internal IP address =
{{Pre}}
$ hostname -I


==== Take a screenshot (and edit them) ====
$ ifconfig  # also works on Android through Termux
See [[#Take_screenshots_.28and_edit_them.29|Take screenshots]].
</pre>
* https://www.raspberrypi.org/documentation/remote-access/ip-address.md


=== [https://cozy.geigi.de/ Cozy] - audiobook player ===
== Private/internal/local IP/network ==
* [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://en.wikipedia.org/wiki/IPv4#Private_networks
* [https://www.lifewire.com/free-audio-books-3481748 Top 14 Websites For Free Audiobooks]


=== ebook readers ===
* 10.0.0.0 – 10.255.255.255
[https://itsfoss.com/best-ebook-readers-linux 7 Best eBook Readers for Linux]: Calibre, FBReader, Okular, Lucidor, Bookworm, Easy Ebook Viewer and Buka.
* 172.16.0.0 – 172.31.255.255
* 192.168.0.0 – 192.168.255.255


==== [http://calibre-ebook.com/download_linux Calibre] - Read ebook in epub format ====
= Get external IP address =
See [[Calibre|Calibre]]
Using a browser: Google.com and type "my ip"


=== RSS reader ===
[https://opensource.com/article/18/5/how-find-ip-address-linux How to find your IP address in Linux]
Some references:
# [https://itsfoss.com/feed-reader-apps-linux/ 5 Best Feed Reader Apps for Linux]
# [https://www.tecmint.com/best-rss-feed-readers-for-linux/ 14 Best RSS Feed Readers for Linux in 2018]. It contains nice screenshots.


Some examples:
[https://askubuntu.com/a/145017 Command for determining my public IP?] '''wget -qO- https://ipecho.net/plain ; echo '''
* [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
* [http://www.rssowl.org/ RSSOwl]. Depends on Java. Cross platform.
* Firefox and Thunderbird have built-in support for RSS.


=== Display/screen ===
[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]
==== 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
https://github.com/jakewmeyer/Geo (one shell script)
<syntaxhighlight lang='bash'>
export DISPLAY=:0.0
</syntaxhighlight>
first before calling the '''xset''' command, or use '-display' argument
<syntaxhighlight lang='bash'>
xset -display :0.0 dpms force off
xset -display :0.0 dpms force on
</syntaxhighlight>


==== autoxrandr ====
[https://www.makeuseof.com/get-public-ip-address-in-linux/ How to Find the Public IP Address on a Linux System]
Plug your laptop into different monitor setups. https://www.donarmstrong.com/posts/autorandr/


==== Add new screen/display resolutions ====
It seems there is no way to get the external IP address without not using external services.
* 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}}
<syntaxhighlight lang='bash'>
host myip.opendns.com resolver1.opendns.com
xrandr | grep maximum
# Look for the bottom line output  myip.opendns.com has address XXX.XX.XX.XXX
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
</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.
# 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  
</pre>
To store my IP in a shell variable
{{Pre}}
myip="$(dig +short myip.opendns.com @resolver1.opendns.com)"
echo "My WAN/Public IP address: ${myip}"
</pre>


==== Wayland ====
The above only gives the IP. The following method gives geo information too.
* [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)]
{{Pre}}
** “xrandr -o right” command can be used to rotate the screen
curl ipinfo.io # ifconfig.me, icanhazip.com, ipecho.net/plain, ifconfig.co
** But it does not work in Fedora because Fedora uses the Wayland display server rather than xserver.
# OR give a specific IP (domain name does not work)
curl ipinfo.io/216.58.194.46


==== export DISPLAY ====
{
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.
  "ip": "216.58.194.46",
<syntaxhighlight lang='bash'>
  "hostname": "dfw25s12-in-f14.1e100.net",
export DISPLAY=:0.0
  "city": "Mountain View",
</syntaxhighlight>
  "region": "California",
 
  "country": "US",
=== LVM Demystified ===
  "loc": "37.4192,-122.0574",
http://www.linuxjournal.com/content/lvm-demystified
  "org": "AS15169 Google Inc.",
 
  "postal": "94043"
=== See which groups you belong to, id & group commands ===
}
* [https://www.2daygeek.com/how-to-check-which-groups-a-user-belongs-to-on-linux/ How To Check Which Groups A User Belongs To On Linux]
<pre>
groups
groups <username>
</pre>
</pre>


=== groupadd, chgrp, usermod, ACL (access control lists) ===
== IP geolocation ==
* [http://www.tecmint.com/create-a-shared-directory-in-linux/ Create a Shared Directory for All Users in Linux]
Test url: ubuntu.mirrors.pair.com
* [https://www.tecmint.com/give-read-write-access-to-directory-in-linux/ Assign Read/Write Access to a User on Specific Directory in Linux]
* https://iplocation.net
* [https://www.howtoforge.com/linux-chgrp-command/ Linux Chgrp Command for Beginners (5 Examples)]
* command line - input is an IP address
:<syntaxhighlight lang='bash'>
curl https://ipapi.co/8.8.8.8/json/


<syntaxhighlight lang='bash'>
curl https://ipinfo.io/8.8.8.8
sudo mkdir -p /var/www/reports/
</syntaxhighlight>
sudo groupadd project
* command line - input is a web address
 
:<syntaxhighlight lang='bash'>
sudo usermod -a -G project tecmint
IP_ADDRESS=$(dig +short example.com)
sudo chgrp -R project /var/www/reports/
curl https://ipapi.co/$IP_ADDRESS/json/
sudo chmod -R 2775 /var/www/reports/
</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]


create more system users and add them to the directory group as follows:
= Domain, WHOIS =
<syntaxhighlight lang='bash'>
<ul>
sudo useradd -m -c "Aaron" -s/bin/bash -G project aaron
<li>[https://www.whois.net/ WHOIS LOOKUP]. For example, consider "r-pkg.org" domain,
sudo useradd -m -c "John" -s/bin/bash -G project john
<ul>
sudo useradd -m -c "Ravi" -s/bin/bash -G project ravi
<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).
 
= Subnet =
[http://en.wikipedia.org/wiki/IPv4_subnetting_reference 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.


sudo mkdir -p /var/www/reports/aaron_reports
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
sudo mkdir -p /var/www/reports/john_reports
sudo mkdir -p /var/www/reports/ravi_reports
</syntaxhighlight>


=== Shared library management ===
== IPv6 ==
http://www.cyberciti.biz/tips/linux-shared-library-management.html
* [https://en.wikipedia.org/wiki/IPv6_subnetting_reference IPv6]
* [https://www.linux.com/learn/intro-to-linux/2017/11/testing-ipv6-networking-kvm-part-1 Testing IPv6 Networking in KVM: Part 1]
* [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?]


# ldconfig : Updates the necessary links for the run time link bindings.
= ping command =
# ldd : Tells what libraries a given program needs to run.
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.
# ltrace : A library call tracer.
# ld.so/ld-linux.so: Dynamic linker/loader.


=== Install binary software using sudo ===
== Check if a server is up/down if pining to that machine is not allowed ==
One example ([http://calibre-ebook.com/download_linux Calibre]) is like
Hint: use nmap to scan open ports
<pre>
<pre>
sudo -v && wget -nv -O- https://raw.githubusercontent.com/kovidgoyal/calibre/master/setup/linux-installer.py | \
nmap -PS22 -p22 <hostname> # port 22 only
sudo python -c "import sys; main=lambda:sys.stderr.write('Download failed\n'); exec(sys.stdin.read()); main()"
# OR
nc -z -v <hostname> 22
</pre>
</pre>
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.
If the option "-O-" is not used, we'd better to use "-N" option in wget to overwrite an existing file.
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].


[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>
<pre>
      -O file
if nc -z $server 22 2>/dev/null; then
      --output-document=file
    echo "$server ✓"
          The documents will not be written to the appropriate files, but all
else
          will be concatenated together and written to file.  If - is used as
    echo "$server ✗"
          file, documents will be printed to standard output, disabling link
fi
          conversion.  (Use ./- to print to a file literally named -.)
</pre>
</pre>


=== Log files ===
[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]
[https://www.digitalocean.com/community/articles/how-to-view-and-configure-linux-logs-on-ubuntu-and-centos DigitalOcean]
<syntaxhighlight lang='bash'>
$ ls -lt /var/log
</syntaxhighlight>


==== ssh log files: '''/var/log/auth.log''' ====
== Check if Sites are Online using a PHP script ==
* /var/log/syslog
[https://www.makeuseof.com/how-to-use-crontab-linux/ How to Use Crontab to Automate Repetitive Tasks in Linux]
* /var/log/auth.log: it includes ssh log in information and lots of CRON sessions opened and closed ''every minutes''.


And
= Build a home network =
* [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://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://ubuntuforums.org/showthread.php?t=1256801 remove cron from /var/log/auth.log]
* http://rbgeek.wordpress.com/2012/05/14/ubuntu-as-a-firewallgateway-router/
* [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)]


==== Apache log ====
== IP Subnet Calculator ==
* /var/log/apache2/error.log (small 83K). Useful to troubleshoot errors/crashes of Apache.
https://www.dan.me.uk/ipsubnets?ip=10.0.0.0
<pre>
grep "May 08" /var/log/apache2/error.log
</pre>
* /var/log/apache2/access.log (large 10M)


==== mail ====
* CIDR block    IP range (network - broadcast)    Subnet Mask    IP Quantity 
/var/log/maillog
* 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


=== '''uptime''' command ===
= How Use Your Router and ISP’s Modem/Router Combo In Tandem =
<syntaxhighlight lang='bash'>
http://www.howtogeek.com/255206/how-use-your-router-and-isps-modemrouter-combo-in-tandem/
uptime
watch -n 60 uptime
</syntaxhighlight>


=== '''timeout''' command ===
= Troubleshoot and repair network problems =
https://www.howtoforge.com/linux-timeout-command/
http://www.linuxuser.co.uk/features/troubleshot-repair-linux-networks


=== Linux command similar to ''top'' to show hard disk activity ===
== Computer 1 can ping Computer 2 but not reverse ==
Use '''iotop'''. On ubuntu, we can use sudo apt-get install to install it. Use '''sudo iotop''' to launch it.
Use the [[#route|route]] command to solve. See also [http://serverfault.com/questions/391954/linux-router-ping-doesnt-route-back this post].
<syntaxhighlight lang='bash'>
sudo apt-get install iotop


sudo iotop -o -u $USER
= Simple Network Management Protocol (snmp) =
</syntaxhighlight>
* https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol
* 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]


Another program is '''iostat''' and the '''-d''' (disk) option. The '''-x''' option will display extension I/O status.
= Monitor network by Cacti (GUI) =
<pre>
* http://www.ubuntugeek.com/install-cacti-monitoring-tool-on-ubuntu-15-10-server.html
sudo apt-get install sysstat
* http://www.cacti.net/
iostat -dx 5 # every 5 seconds
 
</pre>
= Monitor network by command line =
[http://www.thegeekstuff.com/2011/07/iostat-vmstat-mpstat-examples/ 24 iostat, vmstat and mpstat Examples for Linux Performance Monitoring]
[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.
 
== 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
 
== iftop ==
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'''.
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].
 
It is strange that the output shows other devices names in my network.


=== Install [http://hbase.apache.org/ Apache HBase] ===
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.
<pre>
<pre>
$ tar xzvf hbase-0.98.3-hadoop2-bin.tar.gz
$ dig A pandora.com
$ cd hbase-0.98.3-hadoop2/
$ ipcalc -b 208.85.40.20
$ cat conf/hbase-site.xml
$ sudo iftop -F 208.85.40.20/24 -i wlan0
<?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.
== nethogs ==
<pre>
<pre>
$ ls /usr/lib/java
$ sudo nethogs wlan0
$ export JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64
</pre>
</pre>
Note that the last line may be replaced by
[https://askubuntu.com/q/1131621 Why does the snapd service use so much data?]
 
== nload ==
<pre>
<pre>
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:bin/javac::")
nload -m
</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
[https://www.tecmint.com/nload-monitor-linux-network-traffic-bandwidth-usage/ nload – Monitor Linux Network Bandwidth Usage in Real Time]
brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$ ./bin/hbase shell
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'
The result is the same as [[#gtop_command|gtop]] (gtop is cooler) gives.
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
0 row(s) in 2.0770 seconds


=> Hbase::Table - test
== bmon ==
hbase(main):002:0> list 'test'
https://www.tecmint.com/bmon-network-bandwidth-monitoring-debugging-linux/
TABLE                                                                         
test                                                                           
1 row(s) in 0.0530 seconds


=> ["test"]
== [http://humdi.net/vnstat/ vnstat] for network traffic monitor ==
hbase(main):003:0> exit
* [https://www.cyberciti.biz/faq/ubuntu-install-vnstat-console-network-traffic-monitor/ Ubuntu install vnstat console network traffic monitor]
* [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]


brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$ ./bin/hbase
{{Pre}}
# 1. Install vnStat
sudo apt-get install vnstat


shell2014-07-06 09:53:37,480 INFO  [main] Configuration.deprecation: hadoop.native.lib is deprecated. Instead, use io.native.lib.available
# 2. Pick a Interface to Monitor using vnStat
HBase Shell; enter 'help<RETURN>' for list of supported commands.
vnstat -u -i eth0
Type "exit<RETURN>" to leave the HBase Shell
vnstat --iflist
Version 0.98.3-hadoop2, rd5e65a9144e315bb0a964e7730871af32f5018d5, Sat May 31 19:56:09 PDT 2014
vnstatd -d # start the daemon
ps -ef | grep vnst


hbase(main):001:0> list 'test'
# 3. vnStat Basic Usage
TABLE                                                                         
vnstat
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
test                                                                           
1 row(s) in 1.4800 seconds


=> ["test"]
# 4. vnStat hours, days, months, weeks Network Data
hbase(main):002:0> put 'test', 'row1', 'cf:a', 'value1'
vnstat -d
0 row(s) in 0.4460 seconds
vnstat -m


hbase(main):003:0> put 'test', 'row2', 'cf:b', 'value2'
# 5. Export the data to Excel or other DB
0 row(s) in 0.0140 seconds
vnstat --dumpdb


hbase(main):004:0> put 'test', 'row3', 'cf:c', 'value3'
# 6. Display Live Network Statistics
0 row(s) in 0.0050 seconds
vnstat -l
 
# 7. Change the default vnstat output format
vnstat -s (--short)
vnstat --style 0


hbase(main):005:0> scan 'test'
# 8. Display Top 10 Traffic Days
ROW                  COLUMN+CELL                                             
vnstat --top10
row1                column=cf:a, timestamp=1404654837532, value=value1       
</pre>
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'
= Network related linux commands =
COLUMN                CELL                                                     
* [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.
cf:a                timestamp=1404654837532, value=value1                   
* [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
1 row(s) in 0.0280 seconds


hbase(main):007:0> disable 'test'
== nmcli and nmtui (useful for getting DNS IPs) ==
0 row(s) in 1.6050 seconds
* [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
** [https://kifarunix.com/connect-to-wifi-in-linux-using-nmcli-command/ Connect to WiFi in Linux Using NMCLI command]
** [https://www.tecmint.com/nmcli-connect-wi-fi-from-linux-terminal/ How to Connect Wi-Fi from Linux Terminal Using Nmcli Command]


hbase(main):008:0> drop 'test'
{{Pre}}
0 row(s) in 0.2290 seconds
# Find the up network adaptors
$ nmcli dev status
DEVICE          TYPE      STATE        CONNECTION       
docker0          bridge    connected    docker0           
eno1            ethernet  connected    Wired connection 1


hbase(main):009:0> exit
# Find the DNS
brb@brb-P45T-A:~/Downloads/hbase-0.98.3-hadoop2$
$ nmcli dev show | grep 'IP4.DNS'
</pre>
</pre>


=== [http://daniel.haxx.se/docs/curl-vs-wget.html curl vs wget] ===
== iwconfig ==
<syntaxhighlight lang='bash'>
[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]
sudo apt-get install curl
</syntaxhighlight>
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 wget with '''-o''' will not work in this case. Note with curl, we can also use the '''-O''' (capital O) option which will write output to a local file named like the remote file.
<syntaxhighlight lang='bash'>
curl \
http://travel.nationalgeographic.com/u/TvyamNb-BivtNwcoxtkc5xGBuGkIMh_nj4UJHQKuoXEsSpOVjL0t9P0vY7CvlbxSYeJUAZrEdZUAnSJk2-sJd-XIwQ_nYA/ \
-o owl.jpg
</syntaxhighlight>


[https://www.lifewire.com/curl-definition-2184508 Should I Use Curl Or Wget?] and [https://daniel.haxx.se/docs/curl-vs-wget.html curl vs Wget]
Getting information ('''Link Quality''', '''Signal level''') about the wireless.
* The main benefit of using the wget command is that it can be used to recursively download files.
<pre>
* The curl command lets you use wildcards to specify the URLs you wish to retrieve. And curl supports more [https://curl.haxx.se/docs/manpage.html protocols] than wget (HTTP, HTTPS, FTP) does.
sudo iwconfig
* <strike>The wget command can recover when a download fails whereas the curl command cannot.</strike>
</pre>


Actually [https://curl.haxx.se/mail/archive-2010-10/0001.html curl] supports [https://www.cyberciti.biz/faq/curl-command-resume-broken-download/ continuous downloading] too. But not all FTP connection supports continuous downloading. The following examples show it is possible to use the continuous downloading option in wget/curl for downloading file from ncbi FTP but not from illumina FTP.
See link quality continuously on screen
<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>
$ wget -c ftp://igenome:[email protected]/Drosophila_melanogaster/Ensembl/BDGP6/Drosophila_melanogaster_Ensembl_BDGP6.tar.gz
watch -n 1 cat /proc/net/wireless
--2017-04-13 10:46:16--  ftp://igenome:*password*@ussd-ftp.illumina.com/Drosophila_melanogaster/Ensembl/BDGP6/Drosophila_melanogaster_Ensembl_BDGP6.tar.gz
</pre>
          => ‘Drosophila_melanogaster_Ensembl_BDGP6.tar.gz’
Resolving ussd-ftp.illumina.com (ussd-ftp.illumina.com)... 66.192.10.36
Connecting to ussd-ftp.illumina.com (ussd-ftp.illumina.com)|66.192.10.36|:21... connected.
Logging in as igenome ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /Drosophila_melanogaster/Ensembl/BDGP6 ... done.
==> SIZE Drosophila_melanogaster_Ensembl_BDGP6.tar.gz ... 762893718
==> PASV ... done.    ==> REST 1706053 ...
REST failed, starting from scratch.
==> RETR Drosophila_melanogaster_Ensembl_BDGP6.tar.gz ... done.
Length: 762893718 (728M), 761187665 (726M) remaining (unauthoritative)
0% [                                                                                                                  ] 374,832    79.7KB/s  eta 2h 35m ^C
$ curl -L -O -C - ftp://igenome:[email protected]/Drosophila_melanogaster/Ensembl/BDGP6/Drosophila_melanogaster_Ensembl_BDGP6.tar.gz
** Resuming transfer from byte position 1706053
  % Total    % Received % Xferd  Average Speed  Time    Time    Time  Current
                                Dload  Upload  Total  Spent    Left  Speed
  0  727M    0    0    0    0      0      0 --:--:--  0:00:01 --:--:--    0
curl: (31) Couldn't use REST


$ wget -c ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b147_GRCh37p13/VCF/common_all_20160601.vcf.gz
== (GUI) NetworkManager ==
--2017-04-13 10:52:02--  ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b147_GRCh37p13/VCF/common_all_20160601.vcf.gz
ps -ef | grep NetworkManager
          => ‘common_all_20160601.vcf.gz’
Resolving ftp.ncbi.nih.gov (ftp.ncbi.nih.gov)... 2607:f220:41e:250::7, 130.14.250.10
Connecting to ftp.ncbi.nih.gov (ftp.ncbi.nih.gov)|2607:f220:41e:250::7|:21... connected.
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /snp/organisms/human_9606_b147_GRCh37p13/VCF ... done.
==> SIZE common_all_20160601.vcf.gz ... 1023469198
==> EPSV ... done.    ==> RETR common_all_20160601.vcf.gz ... done.
Length: 1023469198 (976M) (unauthoritative)
24% [===========================>                                                                                      ] 255,800,120 55.2MB/s  eta 15s    ^C
$ wget -c ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b147_GRCh37p13/VCF/common_all_20160601.vcf.gz
--2017-04-13 10:52:11--  ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b147_GRCh37p13/VCF/common_all_20160601.vcf.gz
          => ‘common_all_20160601.vcf.gz’
Resolving ftp.ncbi.nih.gov (ftp.ncbi.nih.gov)... 2607:f220:41e:250::7, 130.14.250.10
Connecting to ftp.ncbi.nih.gov (ftp.ncbi.nih.gov)|2607:f220:41e:250::7|:21... connected.
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /snp/organisms/human_9606_b147_GRCh37p13/VCF ... done.
==> SIZE common_all_20160601.vcf.gz ... 1023469198
==> EPSV ... done.    ==> REST 267759996 ... done.   
==> RETR common_all_20160601.vcf.gz ... done.
Length: 1023469198 (976M), 755709202 (721M) remaining (unauthoritative)
47% [++++++++++++++++++++++++++++++========================>                                                            ] 491,152,032 50.6MB/s  eta 12s    ^C


$ curl -L -O -C - ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b147_GRCh37p13/VCF/common_all_20160601.vcf.gz
== ifconfig - spoof the hardware address at the software level ==
  % Total    % Received % Xferd  Average Speed  Time    Time    Time  Current
To change the MAC address temporarily on a '''NIC''' (network interface controller),
                                Dload  Upload  Total  Spent    Left  Speed
{{Pre}}
65  976M  65  639M    0    0  83.7M      0  0:00:11 0:00:07  0:00:04 90.4M^C
sudo ifconfig eth0 down
sudo ifconfig eth0 hw ether 00:11:22:33:44:55
sudo ifconfig eth0 up
</pre>
</pre>
And it seems there is no need to modify /etc/network/interfaces.


==== curl man page, supported protocols ====
For wlan
https://curl.haxx.se/docs/manpage.html
{{Pre}}
 
sudo ifconfig wlan0 down
==== wget and username/password ====
sudo ifconfig wlan0 hw ether 00:11:22:33:44:55
http://www.cyberciti.biz/faq/wget-command-with-username-password/
sudo ifconfig wlan0 up
 
</pre>
====  Download and Un-tar(Extract) in One Step ====
If we don't want to avoid saving a temporary file, we can use one piped statement.
<syntaxhighlight lang='bash'>
curl http://download.osgeo.org/geos/geos-3.5.0.tar.bz2 | tar xvz
# OR
wget http://download.osgeo.org/geos/geos-3.5.0.tar.bz2 -O - | tar jx


# For .gz file
See
wget -O - ftp://ftp.direcory/file.gz | gunzip -c > gunzip.out
* [http://www.thegeekstuff.com/2009/03/ifconfig-7-examples-to-configure-network-interface 7 Examples To Configure Network Interface]
</syntaxhighlight>
* [http://www.tecmint.com/ifconfig-command-examples/ 15 Useful “ifconfig” Commands to Configure Network Interface in Linux]
See [http://www.shellhacks.com/en/HowTo-Download-and-Extract-untar-TAR-Archive-with-One-Command shellhacks.com]. Note that the magic part of the [https://www.gnu.org/software/wget/ wget option "-O -"]; it will ''output'' the document to the standard output instead of a file.
* [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?]


The "-c" in gunzip is to have [https://stackoverflow.com/questions/16262980/redirect-pipe-wget-download-directly-into-gunzip?answertab=active#tab-top gzip output to the console]. PS. it seems not necessary to use the "-c" option.
== ip command ==
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].


==== Download and execute the script in one step ====
[https://www.cyberciti.biz/faq/linux-ip-command-examples-usage-syntax/# Linux ip Command Examples]
See [http://stackoverflow.com/questions/5735666/execute-bash-script-from-url Execute bash script from URL].
<syntaxhighlight lang='bash'>
curl -s https://server/path/script.sh | sudo sh


curl -s http://server/path/script.sh | sudo bash /dev/stdin arg1 arg2
http://www.makeuseof.com/tag/networking-commands-linux-terminal/
{{Pre}}
ip a
ip addr
ip address show


sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin
ip link set DEVICE down # eg ip link set eth0 down
</syntaxhighlight>


==== curl and POST request ====
ip link set DEVICE up
* http://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request
</pre>
* https://learn.adafruit.com/raspberry-pi-physical-dashboard?view=all (the original post I saw)
* http://conqueringthecommandline.com/book/curl


==== curl and proxy ====
== iptables ==
[https://www.cyberciti.biz/faq/linux-unix-curl-command-with-proxy-username-password-http-options/ How to use curl command with proxy username/password on Linux/ Unix]
* 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]


==== Website performance ====
== route ==
[http://www.tecmint.com/httpstat-curl-statistics-tool-check-website-performance/ httpstat – A Curl Statistics Tool to Check Website Performance]
[http://www.thegeekstuff.com/2012/04/route-examples/ 7 Linux Route Command Examples]


==== wget/curl a file with correct name when redirected ====
# Display Existing Routes ('''route -n''')
<syntaxhighlight lang='bash'>
# Adding a Default Gateway ('''route add default gw 192.168.1.1''')
wget --trust-server-names <url>
# List Kernel’s Routing Cache Information ('''route -Cn''')
# Or
# Reject Routing to a Particular Host or Network ('''route add -host 192.168.1.51 reject''')
wget --content-disposition <url>
# 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''')
# Or
# 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''')
curl -JLO <url>
# Allow Internet Access/External World ('''route add default gw 125.250.60.59''')
</syntaxhighlight>


==== wget to download a folder ====
On Ubuntu 16.04, it shows
https://stackoverflow.com/questions/8755229/how-to-download-all-files-but-not-html-from-a-website-using-wget
{{Pre}}
<syntaxhighlight lang='bash'>
$ route
wget -A pdf,jpg,PDF,JPG -m -p -E -k -K -np http://site/path/
Kernel IP routing table
</syntaxhighlight>
Destination    Gateway        Genmask        Flags Metric Ref    Use Iface
 
default        FIOS_Quantum_Ga 0.0.0.0        UG    600    0        0 wlp3s0
==== wget to download a website ====
link-local      *               255.255.0.0    U    1000  0        0 wlp3s0
* http://linux.about.com/od/commands/a/Example-Uses-Of-The-Command-Wget.htm
192.168.1.0    *               255.255.255.0  U    600    0        0 wlp3s0
* https://www.gnu.org/software/wget/manual/wget.html
$ route -n  # showing numerical IP address instead of host name.
 
Kernel IP routing table
To download a copy of a complete web site, use the recursive option ('-r') By default it will go up to five levels deep. You can change the default level by using the '-l' option.  
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
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.
169.254.0.0    0.0.0.0        255.255.0.0    U    1000  0        0 wlp3s0
<syntaxhighlight lang='bash'>
192.168.1.0    0.0.0.0        255.255.255.0  U    600    0        0 wlp3s0
wget -p --convert-links -r -l2 linux.about.com -o logfile
</pre>
wget -p --convert-links -r -l1 https://csgillespie.github.io/efficientR # create csgillespie/efficientR
Flag value 'U' means ''up'' and 'G' means ''gateway'.
</syntaxhighlight>


=== Torrent ===
== Connect two networks ==
==== [https://github.com/kryptxy/torrench Torrench] ====
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.
[https://fossbytes.com/review-torrench-download-torrents-using-terminal-linux/ Torrench: How To Search And Download Torrent Files Using Terminal (Linux, Mac, Windows)]


==== aria2 - command line downloader supports torrents and multi-connection ====
For example, my network structure is
[http://www.2daygeek.com/aria2-command-line-download-utility-tool/ aria2 command examples]
* 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


The '''-x''' argument helps a little bit.
By default, PC2 can ssh to PC1 but PC1 cannot access PC2.
<pre>
# 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
</pre>


=== Axel ===
The following command will solve the problem that PC1 cannot access PC2:
It can create an unlimited number of worker threads to download any kind of data.  
{{Pre}}
See https://www.beginnersheap.com/top-5-command-line-download-accelerators-linux/
# 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


=== [http://lftp.yar.ru/ lftp] ===
$ netstat -rn
* [http://www.linuxquestions.org/questions/linux-software-2/command-line-ftp-client-94510/ It supports FXP (site-to-site transfers) and dropping to background]
Kernel IP routing table
* [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.
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
=== Apply a patch to source code ===
192.168.1.0    0.0.0.0        255.255.255.0  U        0 0          0 eth0
* http://www.cyberciti.biz/faq/appy-patch-file-using-patch-command/.  
192.168.2.0    192.168.1.ASUS  255.255.255.0  UG        0 0          0 eth0
* http://www.thegeekstuff.com/2014/12/patch-command-examples/
</pre>


For example [https://groups.google.com/forum/#!topic/tuxedo-tools-users/BVNDDmInU0A Tophat 2.0.12 compatibility with Samtools 1.0],
[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.
<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/
== traceroute ==
tophat-2.0.12/src/tophat.py:def check_samtools():
{{Pre}}
tophat-2.0.12/src/tophat.py:        check_samtools()
sudo apt-get install traceroute
 
traceroute 8.8.8.8
brb@brb-VirtualBox:~/Downloads$ cp support_for_tophat_1.patch tophat-2.0.12/src/
brb@brb-VirtualBox:~/Downloads$ cd tophat-2.0.12/src/
brb@brb-VirtualBox:~/Downloads/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).
brb@brb-VirtualBox:~/Downloads/tophat-2.0.12/src$ ls
</pre>
</pre>


=== IP address fundamental ===
On Windows, we can use the '''tracert''' command. For example, '''tracert www.microsoft.com'''.
http://www.howtogeek.com/133943/geek-school-learning-windows-7-ip-addressing-fundamentals/.  


There are three classes for private IP ranges.
== nslookup (convert between hostname and ip) and host ==
* 10.0.0.1 – 10.255.255.254 from Class A
* https://en.wikipedia.org/wiki/Nslookup
* 172.16.0.1 – 172.31.255.254 from Class B
* https://en.wikipedia.org/wiki/Host_(Unix)
* 192.168.0.1 – 192.168.255.254 from Class C
* [https://stackoverflow.com/a/24196970 How to get hostname from IP (Linux)?]


[[#Subnet|Subnet]]
{{Pre}}
$ 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.


=== Get internal IP address ===
$ nslookup google.com
<syntaxhighlight lang='bash'>
Server:        127.0.1.1
$ hostname -I
Address:        127.0.1.1#53
</syntaxhighlight>
 
* https://www.raspberrypi.org/documentation/remote-access/ip-address.md
Non-authoritative answer:
Name:  google.com
Address: 172.217.7.238
</pre>
<pre>
mac$ nslookup cran.r-project.org
Server: 156.40.70.10
Address: 156.40.70.10#53


=== Get external IP address ===
Non-authoritative answer:
[https://opensource.com/article/18/5/how-find-ip-address-linux How to find your IP address in Linux]
cran.r-project.org canonical name = cran.wu-wien.ac.at.
Name: cran.wu-wien.ac.at
Address: 137.208.57.37


https://www.iplocation.net or https://www.ipify.org/
mac$ nslookup 137.208.57.37
Server: 156.40.70.10
Address: 156.40.70.10#53


https://github.com/jakewmeyer/Geo (one shell script)
Non-authoritative answer:
37.57.208.137.in-addr.arpa name = cran.wu-wien.ac.at.
</pre>


It seems there is no way to get the external IP address without not using external services.
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.
<syntaxhighlight lang='bash'>
# http://unix.stackexchange.com/questions/22615/how-can-i-get-my-external-ip-address-in-a-shell-script
sudo apt-get install dnsutils
dig +short myip.opendns.com @resolver1.opendns.com
# OR
curl http://ipecho.net/plain; echo
# OR
curl ipv4.ipogre.com 
</syntaxhighlight>
To store my IP in a shell variable
<syntaxhighlight lang='bash'>
myip="$(dig +short myip.opendns.com @resolver1.opendns.com)"
echo "My WAN/Public IP address: ${myip}"
</syntaxhighlight>


The above only gives the IP. The following method gives geo information too.
== dig ==
<syntaxhighlight lang='bash'>
[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.  
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


{
{{Pre}}
  "ip": "216.58.194.46",
$ sudo apt-get install dnsutils
  "hostname": "dfw25s12-in-f14.1e100.net",
$ dig world.std.com
  "city": "Mountain View",
; <<>> DiG 9.9.5-3ubuntu0.16-Ubuntu <<>> google.com
  "region": "California",
;; global options: +cmd
  "country": "US",
;; Got answer:
  "loc": "37.4192,-122.0574",
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49227
  "org": "AS15169 Google Inc.",
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
  "postal": "94043"
}
</syntaxhighlight>


==== IP geolocation ====
;; OPT PSEUDOSECTION:
Test url: ubuntu.mirrors.pair.com
; EDNS: version: 0, flags:; udp: 512
* https://www.ipligence.com/geolocation
;; QUESTION SECTION:
* http://www.ipfingerprints.com/
;google.com.                   IN      A
* 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://www.iplocation.net/ (not work)
* http://geobytes.com/iplocator/ (not work)
* [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.


=== Domain ===
;; ANSWER SECTION:
* [https://www.whois.net/ WHOIS LOOKUP]. For example, consider "r-pkg.org" domain,
google.com.             130    IN      A      172.217.5.238
** The 'Sponsoring Registrar' shows who is the sponsoring registrar (eg GoDaddy.com).
** The 'Registrant Name' shows who registered this domain.
** Command Line Interface.  
<syntaxhighlight lang='bash'>
sudo apt-get install whois
whois r-pkg.org
</syntaxhighlight>
* [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 ===
;; Query time: 11 msec
[http://en.wikipedia.org/wiki/IPv4_subnetting_reference IPv4]
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Fri Dec 01 17:32:37 EST 2017
;; MSG SIZE  rcvd: 55
</pre>


* Class A:  255.0.0.0 or /8;
== arp (Address Resolution Protocol) ==
* Class B, 255.255.0.0 or /16;
The '''arp ''' command can be used to show the MAC addresss of all hosts in LAN
* Class C, 255.255.255.0 or /24.
{{Pre}}
arp -a
</pre>


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.
== 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>
echo >/dev/tcp/google.com/80;
if [ $? -eq 0 ]; then echo "Connection Successful"; fi
</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
= Find open ports =


[https://en.wikipedia.org/wiki/IPv6_subnetting_reference IPv6]
{| class="wikitable"
! command
! example
! comment
|-
| ss
| ss -lnt <br />
sudo ss -tulpn &#124; grep LISTEN
| contain pid, <br />
add "sudo" can show program/command names on the last column
|-
| 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.
|-
| '''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.
|}


* [https://www.linux.com/learn/intro-to-linux/2017/11/testing-ipv6-networking-kvm-part-1 Testing IPv6 Networking in KVM: Part 1]
== Socket ==
[https://www.cloudsavvyit.com/1263/what-are-unix-sockets-and-how-do-they-work/ What Are Unix Sockets and How Do They Work]


=== ping command ===
== nmap/network mapper - port scanning & IPs in local network ==
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.
[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


=== Build a home network ===
cd /usr/share/nmap
* [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)
sudo wget https://svn.nmap.org/nmap/nmap-os-db
* http://rbgeek.wordpress.com/2012/05/14/ubuntu-as-a-firewallgateway-router/
</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


==== IP Subnet Calculator ====
nmap 192.168.1.100  # does not require root privileges
https://www.dan.me.uk/ipsubnets?ip=10.0.0.0
                    # used to check open ports


* CIDR block    IP range (network - broadcast)    Subnet Mask    IP Quantity 
nmap 192.168.1.*     # show IPs and ports in LAN
* 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 ===
sudo nmap -sP 192.168.1.1/24 # show connected IPs (no hostnames?) and MAC addresses
http://www.howtogeek.com/255206/how-use-your-router-and-isps-modemrouter-combo-in-tandem/
                            # 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


=== Troubleshoot and repair network problems ===
nmap -T4 -F 192.168.1.99-255 # show connected IPs and open ports
http://www.linuxuser.co.uk/features/troubleshot-repair-linux-networks
                            # -F means fast
nmap -F taichimd.us  # Note that domain name != server
nmap -v taichimd.us


==== Computer 1 can ping Computer 2 but not reverse ====
nmap -A 192.168.1.1  # Aggressive scan (more output)
Use the [[#route|route]] command to solve. See also [http://serverfault.com/questions/391954/linux-router-ping-doesnt-route-back this post].


=== Simple Network Management Protocol (snmp) ===
nmap -p http,ssh,mysql taichimd.us  # scan ports/services
* https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol
                                    # note that mysql will be shown as closed
* Default port number is 161
                                    # ssh port is not correct.
* [https://linoxide.com/how-tos/snmp-installation-linux-server/ What Is SNMP? How To Install & Configure SNMP in Linux]
                                    # Not sure how to get the correct ssh port using nmap
* [http://www.it-slav.net/blogs/2009/02/05/install-and-configure-snmp-on-ubuntu/ Install and configure SNMP on Ubuntu]
nmap --open taichimd.us  # scan open ports
* [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]


=== Monitor network by Cacti (GUI) ===
sudo nmap -traceroute nih.gov
* http://www.ubuntugeek.com/install-cacti-monitoring-tool-on-ubuntu-15-10-server.html
* http://www.cacti.net/


=== Monitor network by command line ===
sudo nmap -sS -O 192.168.1.99 # -O shows operating system
[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.
                              # eth0 MAC


==== iftop ====
$ nmap localhost # showing the true ports from the server
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'''.
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].
Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-09 15:01 EDT
 
Nmap scan report for localhost (127.0.0.1)
It is strange that the output shows other devices names in my network.
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


<pre>
$ nmap localhost -p 3838-4000  # Shiny
$ dig A pandora.com
$ ipcalc -b 208.85.40.20
$ sudo iftop -F 208.85.40.20/24 -i wlan0
</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>


==== nethogs ====
== netstat: get a list of all open ports ==
<pre>
[https://www.ghacks.net/2018/03/21/how-to-use-netstat-in-gnu-linux/ How to use netstat in GNU/Linux]
$ sudo nethogs wlan0
 
*    -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
 
{{Pre}}
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
</pre>
</pre>


==== nload ====
Other commands
<pre>
{{Pre}}
nload -m
sudo lsof -i -P -n | grep LISTEN
sudo ss -tulpn
sudo netstat -tulpn | grep LISTEN
sudo netstat -tulpn  # include dhcpcd & avahi-daemon
</pre>
</pre>


[https://www.tecmint.com/nload-monitor-linux-network-traffic-bandwidth-usage/ nload – Monitor Linux Network Bandwidth Usage in Real Time]
== ss command ==
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'''.


The result is the same as [[#gtop_command|gtop]] (gtop is cooler) gives.
[https://www.howtogeek.com/681468/how-to-use-the-ss-command-on-linux/ How to Use the ss Command on Linux]


==== bmon ====
== lsof command ==
https://www.tecmint.com/bmon-network-bandwidth-monitoring-debugging-linux/
[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?


==== [http://humdi.net/vnstat/ vnstat] ====
<pre>
http://www.thegeekstuff.com/2011/11/vnstat-network-traffic-monitor/
# Basic lsof Output
sudo su
lsof | head -n10


<syntaxhighlight lang='bash'>
lsof -i  # this gives a more list than nmap command
# 1. Install vnStat
</pre>
sudo apt-get install vnstat


# 2. Pick a Interface to Monitor using vnStat
== Common ports ==
vnstat -u -i eth0
* [https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers List of TCP and UDP port numbers]
vnstat --iflist
** Well-known ports: 0 to 1023
vnstatd -d # start the daemon
** Registered ports: 1024 to 49151
ps -ef | grep vnst
** 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]


# 3. vnStat Basic Usage
= Copy text to a clipboard to be used in other apps =
vnstat
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


# 4. vnStat hours, days, months, weeks Network Data
cat ~/.ssh/id_rsa.pub | xclip -sel clip
vnstat -d
</pre>
vnstat -m
Works.


# 5. Export the data to Excel or other DB
= Start Emacs without X =
vnstat --dumpdb
Add '''-nw''' (no window) option.
<pre>
emacs -nw
</pre>


# 6. Display Live Network Statistics
= Audio =
vnstat -l
== 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.


# 7. Change the default vnstat output format
== mp3 codecs ==
vnstat -s (--short)
https://help.ubuntu.com/community/RestrictedFormats
vnstat --style 0
{{Pre}}
sudo apt-get install ubuntu-restricted-extras
</pre>
 
== Concatenate mp3 files ==
{{Pre}}
sudo apt-get install mp3wrap
mp3wrap output.mp3 *.mp3
</pre>


# 8. Display Top 10 Traffic Days
== Reduce the size of an mp3 file ==
vnstat --top10
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>
{{Pre}}
lame --mp3input -b 128 input.mp3 output.mp3
</pre>


=== Network related linux commands ===
== Convert ogg to mp3 ==
==== ifconfig - spoof the hardware address at the software level ====
'''ffmpeg''' is not included in Ubuntu repository. Use the '''avconv''' command. http://superuser.com/questions/15327/how-to-convert-ogg-to-mp3
To change the MAC address temporarily on a '''NIC''' (network interface controller),
{{Pre}}
<syntaxhighlight lang='bash'>
sudo apt-get install libav-tools
sudo ifconfig eth0 down
avconv -i input.ogg -c:a libmp3lame -q:a 2 output.mp3
sudo ifconfig eth0 hw ether 00:11:22:33:44:55
</pre>
sudo ifconfig eth0 up
</syntaxhighlight>
And it seems there is no need to modify /etc/network/interfaces.


For wlan
== Convert m4a/webm to mp3 ==
<syntaxhighlight lang='bash'>
{{Pre}}
sudo ifconfig wlan0 down
avconv -i input.m4a output.mp3
sudo ifconfig wlan0 hw ether 00:11:22:33:44:55
</pre>
sudo ifconfig wlan0 up
</syntaxhighlight>


See
== Remove the vocals from any song using Audacity ==
* [http://www.thegeekstuff.com/2009/03/ifconfig-7-examples-to-configure-network-interface 7 Examples To Configure Network Interface]
https://www.makeuseof.com/tag/remove-vocals-song-audacity/
* [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?]


==== ip command ====
== How to Remove Ambient Noise From Audio Files Using Audacity ==
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].
[https://www.makeuseof.com/tag/remove-ambient-noise-audio-files-audacity/ How to Remove Ambient Noise From Audio Files Using Audacity]


http://www.makeuseof.com/tag/networking-commands-linux-terminal/
== Normalize the volume of an audio file ==
<syntaxhighlight lang='bash'>
* [http://www.howtogeek.com/280739/can-you-losslessly-increase-the-volume-of-mp3-files/ Can You Losslessly Increase the Volume of MP3 Files?]
ip a
* Use [http://www.thebest3d.com/audacity/tutorials/make-louder/audacity-tutorial-make-louder-more-volume-increased-amplitude.html Audacity]. To raise (Amplify) volume:
ip addr
*# Edit > Select All.
ip address show
*# 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.
*# 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].
{{Pre}}
avconv -ss 00:00:10 -i OLD.mp3 -vol 2560 NEW.mp3
</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.
* 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).
{{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>
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.


ip link set DEVICE down # eg ip link set eth0 down
== cut, delete or trim an audio ==
# Open the audio file in audacity.
# select a region in the '''waveform''' area. Do not select in the time interval area (above the waveform).
## 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
## 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.
## To move around the track, use the scrollbar (below the waveform and above the bottom toolbar, not quite clear in Ubuntu/Unity)
# Click Edit -> Remove Audio or labels -> Cut/Delete/Trim Audio
# play the new audio by clicking the green triangle.
# File -> Export -> mp3 format.


ip link set DEVICE up
Helpful resource for Audacity.
</syntaxhighlight>
# Different [http://manual.audacityteam.org/o/man/toolbars_overview.html Toolbars]
# [http://manual.audacityteam.org/o/man/tutorial_editing_an_existing_file.html Tutorial - Editing an Existing Audio File]
 
== Fade out at the end of an audio ==
# Select a region.
# Effect -> Fade out


==== iptables ====
= Wireshark =
* See the [[#ufw_.28uncomplicated_firewall.29|ufw]] command which provides an easy way to configure iptables.
* http://www.howtogeek.com/204458/why-you-shouldn%E2%80%99t-use-mac-address-filtering-on-your-wi-fi-router/
* [https://kerneltalks.com/howto/how-to-disable-iptables-firewall-temporarily/ How to disable iptables firewall temporarily]
* 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>
sudo apt-get install wireshark
sudo chmod 4711 `which dumpcap`
</pre>
* [https://www.youtube.com/watch?v=8PuUnQCS7DQ Wireshark & Rtmpdump - Sniffing RTMP Streams - Ubuntu 10.10]


==== route ====
= Track the Time a Command Takes =
[http://www.thegeekstuff.com/2012/04/route-examples/ 7 Linux Route Command Examples]
[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]


# Display Existing Routes ('''route -n''')
== time command ==
# Adding a Default Gateway ('''route add default gw 192.168.1.1''')
* [https://stackoverflow.com/a/556411 What do 'real', 'user' and 'sys' mean in the output of time(1)?]
# List Kernel’s Routing Cache Information ('''route -Cn''')
* [https://www.howtoforge.com/linux-time-command/ Linux time Command Tutorial for Beginners (with Examples)]
# Reject Routing to a Particular Host or Network ('''route add -host 192.168.1.51 reject''')
{{Pre}}
# 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''')
time COMMAND
# 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''')
time (COMMAND1; COMMAND2)
# Allow Internet Access/External World ('''route add default gw 125.250.60.59''')
time (COMMAND1 && COMMAND2)


On Ubuntu 16.04, it shows
help time
<syntaxhighlight lang='bash'>
</pre>
$ route
 
Kernel IP routing table
When I run a set of 7 jobs using parallel, time command gives an output
Destination    Gateway        Genmask        Flags Metric Ref    Use Iface
<pre>
default        FIOS_Quantum_Ga 0.0.0.0        UG    600    0        0 wlp3s0
real  15m53.788s # the wall clock time the command took from execution till termination
link-local      *              255.255.0.0    U    1000  0        0 wlp3s0
user  95m20.238s # the time taken by the user space
192.168.1.0    *              255.255.255.0  U    600    0        0 wlp3s0
sys   9m1.320s   # the time taken by kernel space
$ route -n  # showing numerical IP address instead of host name.
</pre>
Kernel IP routing table
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.
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
</syntaxhighlight>
Flag value 'U' means ''up'' and 'G' means ''gateway'.


==== Connect two networks ====
== /usr/bin/time command ==
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.
'''[http://man7.org/linux/man-pages/man1/time.1.html /usr/bin/time]''' provides more information then ''time'' command.
{{Pre}}
man time
</pre>


For example, my network structure is
= Magazines =
* Modem/router: LAN IP 192.168.1.*/24
* [http://www.linuxuser.co.uk/ Linux User & Developer]
* PC1: connect to Modem/router
* [http://www.linuxformat.com/ Linux Format]
* Second router (ASUS) connect to Modem/router: its WAN IP is 192.168.1.ASUS. It's LAN IP 192.168.2.*/24
* [http://www.linux-magazine.com/ Linux Magazine]
* PC2 (raspberry pi): connect to the second router (ASUS): its IP is 192.168.1.212
* [http://www.linuxjournal.com/ Linux Journal]


By default, PC2 can ssh to PC1 but PC1 cannot access PC2.
= Latex =


The following command will solve the problem that PC1 cannot access PC2:
== Editors ==
<syntaxhighlight lang='bash'>
* [https://itsfoss.com/Latex-editors-linux/ 10 Best LaTeX Editors For Linux].
# From PC1
* [http://www.xm1math.net/texmaker/ Texmaker]. R's installr package has a function to install Texmaker. Cross platforms.
$ sudo route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.1.ASUS
* [https://www.tug.org/texworks/ TEXworks]. Cross platforms.
$ ssh pi@192.168.2.212    # 192.168.2.212 is the IP address for the Raspberry Pi
* [http://texstudio.sourceforge.net/ TexStudio]. See a dark theme [https://robjhyndman.com/hyndsight/dark-themes-for-writing/ example].


$ netstat -rn
== Online editing ==
Kernel IP routing table
* [https://latexbase.com/ Latex Base]. You can start to try it without registration. Free accounts cannot publish but still can download.
Destination    Gateway        Genmask        Flags  MSS Window  irtt Iface
* [https://www.overleaf.com/ Overleaf]. Free account for 1GB space.
0.0.0.0        192.168.1.1    0.0.0.0        UG        0 0          0 eth0
* [https://www.sharelatex.com/ ShareLatex]
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
</syntaxhighlight>


[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.
== Missing cls ==
* [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>


==== traceroute ====
== Missing sty ==
<syntaxhighlight lang='bash'>
{{Pre}}
sudo apt-get install traceroute
$ apt-cache search pseudocode
traceroute 8.8.8.8
gpt - G-Portugol is a portuguese structured programming language
</syntaxhighlight>
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>


On Windows, we can use the '''tracert''' command. For example, '''tracert www.microsoft.com'''.
= PDF =
See [[PDF|PDF]].


==== netstat ====
= Flow chart =
[https://www.ghacks.net/2018/03/21/how-to-use-netstat-in-gnu-linux/ How to use netstat in GNU/Linux]
* 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


*    -l or --listening shows only the sockets currently listening for incoming connection.
= Clock =
*    -a or --all shows all sockets currently in use.
== xclock (analog) ==
*    -e    --show extended/additional information
{{Pre}}
*    -t or --tcp shows the tcp sockets.
oclock -geometry 500x500+100+0 &
*    -u or --udp shows the udp sockets.
</pre>
*    -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


<syntaxhighlight lang='bash'>
== oclock (analog) ==
netstat -l            # only listening ports
{{Pre}}
netstat -rn            # displays the system's routing table
oclock -bg blue -geometry 500x500+100+0 -bd purple -transparent &
netstat -at
oclock -bg blue -geometry 500x500+100+0 -bd purple -jewel green &
netstat -ant          # For tcp
</pre>
sudo netstat -pant    # show ports and programs (pant = 喘氣). Best of the best!!!
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.
sudo netstat -peanut  # (output is too wide)
netstat -anp | grep 3306 | wc -l  # print the number of connections for the port mysql port i.e. 3306.
</syntaxhighlight>


==== nmap - port scanning & IPs in local network ====
== dclock (digital) ==
nmap - Network exploration tool and security / port scanner
Digital clock for the X Window System with flexible display.
* 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.
* http://manpages.org/dclock
** Modifying the nmap-os-db Database Yourself
* 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?]]
** 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.
<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+ */ " >
** 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 apt-get install dclock
<syntaxhighlight lang='bash'>
dclock -h
sudo mv /usr/share/nmap/nmap-os-db /usr/share/nmap/nmap-os-db-old
dclock -d
 
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139        # 'q' to quit
cd /usr/share/nmap
dclock -date "Today is %m/%d/%y" -led_off black -bg black -fg yellow -geometry 400x150+0+0 # width x hight + X + Y
sudo wget https://svn.nmap.org/nmap/nmap-os-db
</pre>
</syntaxhighlight>
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.
* http://www.cyberciti.biz/networking/nmap-command-examples-tutorials/
<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+ */ " >
* http://bencane.com/2013/02/25/10-nmap-commands-every-sysadmin-should-know/
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139 &>/dev/null &
* http://www.tecmint.com/nmap-command-examples/
</pre>
<syntaxhighlight lang='bash'>
sudo apt-get install nmap


nmap 192.168.1.99    # does not require root privileges
== Lubuntu digital clock format ==
                    # used to check open ports
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


nmap 192.168.1.*    # show IPs and ports in LAN
%a %m-%d-%y, %I:%M %p
# Mon 05-30-16, 08:31 AM
</pre>


sudo nmap -sP 192.168.1.1/24 # show connected IPs (no hostnames?) and MAC addresses
== xdaliclock (digital) ==
                            # If you don't use 'sudo' only partial devices can be found
https://www.mankier.com/1/xdaliclock
                            # 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
Scaling is not good. Colors is changing with time.
                            # -F means fast
{{Pre}}
nmap -F taichimd.us
xdaliclock -noseconds -cycle  # 'q' to quit
nmap -v taichimd.us
</pre>


nmap -A 192.168.1.1  # Aggressive scan (more output)
== date command ==
<pre>
sudo apt install toilet
sudo apt install figlet
watch -n 60 "date +'%m/%d/%y  %H:%M:%S' | toilet"


nmap -p http,ssh,mysql taichimd.us  # scan ports/services
ls /usr/share/figlet # list of fonts
                                    # note that mysql will be shown as closed
                    # looking for *.tlf
nmap --open taichimd.us   # scan open ports
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


sudo nmap -traceroute nih.gov
watch --color "date +'%m/%d/%y%H:%M:%S' | toilet -f bigmono12 -F metal"


sudo nmap -sS -O 192.168.1.99 # -O shows operating system
while true; do echo "$(date '+%H:%M:%S' | toilet -f bigmono12 -F border --metal)"; sleep 1; done
                              # eth0 MAC
</pre>


$ nmap localhost
= Reminder take a break, relieve eye strain =
[https://github.com/hovancik/stretchly/ Stretchly]. It's open-source and cross-platform. Nodejs is required.


Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-09 15:01 EDT
[http://www.workrave.org/ Workrave] is another choice. The source code is available too.
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
</syntaxhighlight>


A gui version of nmap is called '''[https://nmap.org/zenmap/ Zenmap]'''.
[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


==== nslookup and host ====
= wine =
<syntaxhighlight lang='bash'>
[[Wine|Wine]]
$ 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
= Running Linux in the AWS/Amazon Web Services =
Server:        127.0.1.1
* http://www.linuxuser.co.uk/tutorials/run-linux-in-the-aws-cloud
Address:       127.0.1.1#53


Non-authoritative answer:
= Forum software =
Name:   google.com
* [http://www.simplemachines.org/ Simple Machines® Forum (SMF)]. For example http://pibot.org/forum/
Address: 172.217.7.238
</syntaxhighlight>


==== dig ====
= RAID =
<syntaxhighlight lang='bash'>
* http://www.maximumpc.com/what-every-pc-builder-should-know-about-raid-levels/
$ 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:
= Timer =
; EDNS: version: 0, flags:; udp: 512
* 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.
;; QUESTION SECTION:
;google.com.                   IN      A


;; ANSWER SECTION:
= How to track you laptop using Prey =
google.com.            130    IN      A      172.217.5.238
https://www.howtoforge.com/tutorial/how-to-track-your-linux-laptop/


;; Query time: 11 msec
= last command =
;; SERVER: 127.0.1.1#53(127.0.1.1)
[https://www.howtoforge.com/linux-last-command/ Linux last Command Tutorial for Beginners (8 Examples)]
;; WHEN: Fri Dec 01 17:32:37 EST 2017
;; MSG SIZE  rcvd: 55
</syntaxhighlight>


==== arp (Address Resolution Protocol) ====
== Display a list of system shutdown/reboot date/time ==
The '''arp ''' command can be used to show the MAC addresss of all hosts in LAN
[https://www.cyberciti.biz/tips/linux-last-reboot-time-and-date-find-out.html Linux Find Out Last System Reboot Time and Date Command]
<syntaxhighlight lang='bash'>
<pre>
arp -a
# Works on Linux and Mac
</syntaxhighlight>
last shutdown
last reboot
</pre>


==== nmcli ====
= Automatic reboot after power failure =
* [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]
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.


=== Copy text to a clipboard to be used in other apps ===
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.
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].
<syntaxhighlight lang='bash'>
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
= How to restart/shutdown server safely =
</syntaxhighlight>
[https://www.cyberciti.biz/faq/restart-centos-rhel-safely-and-gracefully/ How to restart CentOS or RHEL server safely]
Works.


=== Start Emacs without X ===
= Wake up and Shut Down Linux Automatically =
Add '''-nw''' (no window) option.
* https://help.ubuntu.com/community/WakeOnLan
<pre>
* https://www.cyberciti.biz/faq/ubuntu-linux-wake-on-lan-client-command-installation-examples/
emacs -nw
* [https://www.linux.com/learn/intro-to-linux/2017/11/wake-and-shut-down-linux-automatically Wake up and Shut Down Linux Automatically]
</pre>


=== Audio ===
Two best options
==== mp3 codecs ====
* Bios: BIOS may have an easy-to-use wakeup scheduler
https://help.ubuntu.com/community/RestrictedFormats
* wakeonlan:  
<syntaxhighlight lang='bash'>
** 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
sudo apt-get install ubuntu-restricted-extras
** 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
</syntaxhighlight>


==== Concatenate mp3 files ====
= BIOS =
<syntaxhighlight lang='bash'>
== Find out BIOS version ==
sudo apt-get install mp3wrap
[https://www.cyberciti.biz/faq/check-bios-version-linux/ Linux Find Out BIOS Version Using a Command Line Option]
mp3wrap output.mp3 *.mp3
</syntaxhighlight>


==== Reduce the size of an mp3 file ====
== How to update Lenovo BIOS from Linux without using Windows ==
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:
https://www.cyberciti.biz/faq/update-lenovo-bios-from-linux-usb-stick-pen/
<syntaxhighlight lang='bash'>
lame --mp3input -b 128 input.mp3 output.mp3
</syntaxhighlight>


==== Convert ogg to mp3 ====
= Internet speed test =
'''ffmpeg''' is not included in Ubuntu repository. Use the '''avconv''' command. http://superuser.com/questions/15327/how-to-convert-ogg-to-mp3
== Web ==
<syntaxhighlight lang='bash'>
* https://fast.com/ (automatically run)
sudo apt-get install libav-tools
* https://www.bing.com/search?q=internet+speed+test
avconv -i input.ogg -c:a libmp3lame -q:a 2 output.mp3
* http://www.speedtest.net/
</syntaxhighlight>
 
== Speedtest-cli ==
See [[Raspberry#Track_Internet_Dropouts|Track_Internet_Dropouts]].
 
{{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
</pre>
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>
    /usr/local/bin/speedtest-cli --share > $log
</pre>
 
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.


==== Convert m4a to mp3 ====
== curl and wget ==
<syntaxhighlight lang='bash'>
[https://osxdaily.com/2013/07/31/speed-test-command-line/ How to Run Speed Test from the Command Line to Check Internet Connection Speed]
avconv -i input.m4a output.mp3
</syntaxhighlight>


==== Remove the vocals from any song using Audacity ====
= '''uname''' - Print system information =
https://www.makeuseof.com/tag/remove-vocals-song-audacity/
* https://www.lifewire.com/display-system-information-uname-command-3964321
* [https://www.networkworld.com/article/3565432/how-to-decipher-linux-release-info.html How to decipher Linux release info]


==== Normalize the volume of an audio file ====
'''uname -a''' will give you
* [http://www.howtogeek.com/280739/can-you-losslessly-increase-the-volume-of-mp3-files/ Can You Losslessly Increase the Volume of MP3 Files?]
* OS (uname = uname -s if you are under a Linux environment)
* Use [http://www.thebest3d.com/audacity/tutorials/make-louder/audacity-tutorial-make-louder-more-volume-increased-amplitude.html Audacity]. To raise (Amplify) volume:
* '''OS (uname -s)''' eg Linux
*# Edit > Select All.
* node name (uname -n=hostname)
*# 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.
* '''kernel release (uname -r)''' eg 3.16.0-38-generic
*# Check clip3. Export > MP3 or just start to listen.
* kernel version (uname -v)
* Command line tool: [https://libav.org/avconv.html avconv] (replace '''ffmpeg''' program). See [http://gfxile.net/z/?p=1343 this post].
* '''machine architecture (uname -m)''' eg x86_64
<syntaxhighlight lang='bash'>
* processor (uname -p)
avconv -ss 00:00:10 -i OLD.mp3 -vol 2560 NEW.mp3
* hardware platform (uname -i)
</syntaxhighlight>
* operating system (uname -o)
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.


==== cut, delete or trim an audio ====
[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?]
# Open the audio file in audacity.
# select a region in the '''waveform''' area. Do not select in the time interval area (above the waveform).
## 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
## 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.
## To move around the track, use the scrollbar (below the waveform and above the bottom toolbar, not quite clear in Ubuntu/Unity)
# Click Edit -> Remove Audio or labels -> Cut/Delete/Trim Audio
# play the new audio by clicking the green triangle.
# File -> Export -> mp3 format.


Helpful resource for Audacity.
= Hardware information =
# Different [http://manual.audacityteam.org/o/man/toolbars_overview.html Toolbars]
* [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]
# [http://manual.audacityteam.org/o/man/tutorial_editing_an_existing_file.html Tutorial - Editing an Existing Audio File]
* [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.


==== Fade out at the end of an audio ====
== Command Line ==
# Select a region.
* [https://opensource.com/article/19/9/linux-commands-hardware-information Linux commands to display your hardware information]
# Effect -> Fade out
* inxi: [https://opensource.com/article/22/9/linux-inxi-command 3 ways to use the Linux inxi command]
** '''inxi -b'''
** '''inxi -W taipei,taiwan'''  (check the weather)
* [https://ostechnix.com/how-to-find-your-system-details-using-inxi/ How To Find Linux System Details Using inxi]


=== Wireshark ===
== hwinfo ==
* http://www.howtogeek.com/204458/why-you-shouldn%E2%80%99t-use-mac-address-filtering-on-your-wi-fi-router/
https://www.2daygeek.com/python-hwinfo-check-display-system-hardware-configuration-information-linux/
* 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>
sudo apt-get install wireshark
sudo chmod 4711 `which dumpcap`
</pre>
 
=== Track the Time a Command Takes ===
[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]


==== time command ====
On Ubuntu, use '''sudo apt install -y hwinfo''' to install hwinfo. [https://lindevs.com/install-hwinfo-on-ubuntu/ Install hwinfo on Ubuntu 20.04]
* [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)]
<syntaxhighlight lang='bash'>
time COMMAND
time (COMMAND1; COMMAND2)
time (COMMAND1 && COMMAND2)
 
help time
</syntaxhighlight>


When I run a set of 7 jobs using parallel, time command gives an output
== dmesg command ==
[https://www.howtogeek.com/449335/how-to-use-the-dmesg-command-on-linux/ How to Use the dmesg Command on Linux]
<pre>
<pre>
real  15m53.788s # the wall clock time the command took from execution till termination
sudo dmesg -L -T
user  95m20.238s # the time taken by the user space
sudo dmesg -L -T --follow  # Watching Live Events
sys  9m1.320s  # the time taken by kernel space
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>
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.
where '''-L''' to is force color output and '''-T''' is to make timestamp human-readable.


==== /usr/bin/time command ====
= Linux Logo and the current system information =
'''[http://man7.org/linux/man-pages/man1/time.1.html /usr/bin/time]''' provides more information then ''time'' command.
* http://www.cyberciti.biz/hardware/howto-display-linux-logo-in-bash-terminal-using-screenfetch-linux_logo/
<syntaxhighlight lang='bash'>
<pre>
man time
odroid@odroid:~$ sudo apt-get install screenfetch
</syntaxhighlight>
odroid@odroid:~$ screenfetch
 
                          ./+o+-      odroid@odroid
=== Magazines ===
                  yyyyy- -yyyyyy+      OS: Ubuntu 15.10 wily
* [http://www.linuxuser.co.uk/ Linux User & Developer]
              ://+//////-yyyyyyo      Kernel: armv7l Linux 3.10.96-77
* [http://www.linuxformat.com/ Linux Format]
          .++ .:/++++++/-.+sss/`      Uptime: 4d 23h 8m
* [http://www.linux-magazine.com/ Linux Magazine]
        .:++o: /++++++++/:--:/-      Packages: 2000
* [http://www.linuxjournal.com/ Linux Journal]
        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++.    


=== Latex ===
odroid@odroid:~$ screenfetch -h
</pre>
* [https://github.com/dylanaraps/neofetch Neofetch], [[:File:NeofetchMac.png]], [[:File:Neofetchpopos.png]]


==== Editors ====
[[File:Neofetch.png|200px]]
* [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].


==== Online editing ====
= Dictionary - [http://artha.sourceforge.net/wiki/index.php/Home Artha] =
* [https://latexbase.com/ Latex Base]. You can start to try it without registration. Free accounts cannot publish but still can download.
* [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.
* [https://www.overleaf.com/ Overleaf]. Free account for 1GB space.
{{Pre}}
* [https://www.sharelatex.com/ ShareLatex]
sudo apt-get install artha
</pre>


==== Missing cls ====
== Translation ==
* [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://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]
* https://tex.stackexchange.com/questions/179214/elsarticle-cls-not-found-when-using-texmaker-but-texlive-latex-extra-is-install/179250
{{Pre}}
<syntaxhighlight lang='rsplus'>
odroid@odroid:~/binary$ ./trans :zh-TW word
$ apt-cache search IEEEtran
word
texlive-publishers - TeX Live: Publisher styles, theses, etc.
/wərd/
</syntaxhighlight>
<syntaxhighlight lang='rsplus'>
sudo apt-get install texlive-publishers
</syntaxhighlight>


==== Missing sty ====
<syntaxhighlight lang='rsplus'>
(Zì)
$ 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
</syntaxhighlight>


=== PDF ===
Definitions of word
==== Change the default viewer ====
[ English -> 正體中文 ]
Right Click(pdf)-> Properties-> Open With-> Okular (or anything) -> Set as default.


==== PDF reader ====
noun
The default one '''Evince''' seems slow when I try to view odroid magazine.
    字
        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


MuPDF is good at speed. Okular is good at annotation.
verb
    為 ... 措辭
        word
odroid@odroid:~/binary$ time ./trans -brief :zh-TW word


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.
real 0m4.249s
 
user 0m2.670s
To change it to be the default program for opening PDF files, right click the file and select Property. Go to the ''Open With'' tab. Choose your file viewer.
sys 0m1.330s
 
<syntaxhighlight lang='bash'>
sudo apt-get install mupdf
</syntaxhighlight>
 
Keyboard shortcuts for mupdf (man mupdf) or http://mupdf.com/docs/manual. Note these are case-sensitive.
<pre>
W    - fit to width
H    - fit to height
L    - rotate page left (clockwise)
R    - rotate page right (counter-clockwise)
12g  - go to page 12
>,<  - go to the next or previous page
+,-  - zoom in or out
/    - search for text
n,N  - Find the next or previous search result.
h,j,k,l - Scroll page left, down, up, or right.
</pre>
</pre>
'''Tip''': to copy a text, use the right mouse button to select a text. Then use Ctrl+c to copy it. It seems it does not work all the time:(


Other pdf viewer choices are
= ASCII art/ word art =
* acroread
* 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]
** Allow to have custom colors for page background and document text.
* 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.
** The custom colors works well on Macbook Pro (2880 x 1440). Background color #494949 and text color #494949.
* http://patorjk.com/software/taag/#p=display&f=Ivrit&t=BRR-SeqTools
* xpdf. old-fashioned. slow.
* evince. slow.
* '''[https://okular.kde.org/ okular]''' (KDE/Qt application)
** Annotation tool such as highlighter is under Tools > Review (F6).
** 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]. Though it works, the result using 'invert colors' option is not good on Dell U2312HM. We can try other option like 'dark & light colors' where we can change the individual colors for the background (say #494949) and text.
** Not as fast as mupdf. It can open a variety of ebook formats.
** MacOS should work but it needs to [https://community.kde.org/Mac install KDE].
** Able to show file properties eg Page Size (eg 50x36 in), Creator (eg PowerPoint), Producer (eg Mac OS X Quartz PDFContext), PDF version (eg 1.3)
* kpdf
* gv
* qpdfview. slow. Used by [https://www.raspberrypi.org/blog/raspbian-update-june-2018/ Raspbian] june 2018.
* Foxit or PDF-XChange Viewer(needs wine)
 
==== PDF crop ====
'''pdfcrop''' (briss is better)
 
https://askubuntu.com/questions/124692/command-line-tool-to-crop-pdf-files
<pre>
<pre>
sudo apt-get install texlive-extra-utils
  ____  ____  ____      ____            _____          _   
 
  | __ )|  _ \| __ )    / ___|  ___  __ |_  _|__   ___ | |___
pdfcrop input.pdf output.pdf # no margins, works but seems too tight
|  _ \| |_) |  _ \ ____\___ \ / _ \/ _` || |/ _ \ / _ \| / __|
 
  | |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
pdfcrop --margins 5 input.pdf output.pdf   # crop pdf but keep 5 bp from each side of page
  |____/|_| \_\____/    |____/ \___|\__, ||_|\___/ \___/|_|___/
 
                                      |_|                   
pdfcrop --margins '5 10 20 30' input.pdf output.pdf  
# left, top, right and bottom margins of 5, 10, 20, and 30 pt
 
# To actually crop something away, use negative values in the argument for crop.
# For example, to crops 50 pts from the left, top, right, bottom (in this order).
pdfcrop --margins '-50 -50 -50 -50' input.pdf output.pdf
</pre>
</pre>
One problem I found is (for newer PDFs with meta data) ''--margins'' initially removes the entire margin before implementing the adjustment. This will cause some pages being chopped out.
* http://patorjk.com/software/taag/#p=display&f=Big&t=BRB-SeqTools
 
'''[https://sourceforge.net/projects/briss/ briss]'''
 
This java program gives me a better control on cropping
# Download the file briss-0.9.tar.gz (8.7 MB) and extract it
# Run '''java -jar briss-0.9.jar'''
# Load the pdf file. It will ask what pages to be excluded from merging (This function does not work). Click 'Cancel' to continue.
# It will automatically create two rectangle areas; one for odd (left) pages and the other for even (right)pages
# Now we work on the left page first. Enlarge the selection to suit our need. Then right click & choose 'Select/Deselect rectangle' (a dash line will be added to the edges of the rectangle) and then 'Copy rectangles'.
# Work on the right page. Right click and choose 'Delete rectangle'. Then 'Paste rectangles'. 
# Now we can click 'Action -> Preview' to preview the result. If we are satisfied with the result, we can click 'Action -> Crop PDF'. Done.
 
==== Remove certain pages ====
https://www.linux.com/learn/manipulating-pdfs-pdf-toolkit
<pre>
<pre>
sudo apt install pdftk
  ____  _____  ____        _____        _______          _   
 
|  _ \|  __ \|  _ \      / ____|      |__  __|        | |   
# remove pages 10 to 25 from a PDF file
| |_) | |__) | |_) |____| (___  ___  __ _| | ___  ___ | |___
pdftk myDocument.pdf cat 1-9 26-end output removedPages.pdf
|  _ <|  _  /|  _ <______\___ \ / _ \/ _` | |/ _ \ / _ \| / __|
 
| |_) | | \ \| |_) |    ____) |  __/ (_| | | (_) | (_) | \__ \
# remove the last page
|____/|_|  \_\____/    |_____/ \___|\__, |_|\___/ \___/|_|___/
pdftk infile.pdf cat 1-r2 output outfile.pdf
                                        | |                   
 
                                        |_|                   
# remove the last 2 pages
pdftk infile.pdf cat 1-r3 output outfile.pdf
</pre>
</pre>
 
* http://patorjk.com/software/taag/#p=display&f=Small&t=BRB-SeqTools
==== PDF highlight and annotation ====
Install [https://docs.kde.org/stable/en/kdegraphics/okular/annotations.html Okular] by
<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
# 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)
# 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)
 
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].
 
==== Merge multiple pdf files into one pdf file ====
https://stackoverflow.com/questions/2507766/merge-convert-multiple-pdf-files-into-one-pdf
<pre>
<pre>
pdfunite in-1.pdf in-2.pdf in-n.pdf out.pdf
  ___ ___ ___    ___          _____        _   
| _ ) _ \ _ )___/ __| ___ __ |_  _|__  ___| |___
| _ \  / _ \___\__ \/ -_) _` || |/ _ \/ _ \ (_-<
|___/_|_\___/  |___/\___\__, ||_|\___/\___/_/__/
                            |_|                 
</pre>
</pre>


==== Arrange, merge, split, rotate, crop ====
= Software that scan Malware and rootkits =
[https://www.linuxuprising.com/2018/12/pdfarranger-merge-split-rotate-crop-or.html PDFArranger: Merge, Split, Rotate, Crop Or Rearrange PDF Documents (PDF-Shuffler Fork) ]
* https://www.howtoforge.com/tutorial/how-to-scan-linux-for-malware-and-rootkits/


==== Editing ====
= Text to speech =
[http://xournal.sourceforge.net/ Xournal]
* 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


==== Print multiple pages per sheet: [https://linux.die.net/man/1/pdfnup pdfnup] ====
= VPN =
The program is similar to psnup.
[[Ubuntu#VPN|Ubuntu -> VPN]]
<pre>
sudo apt install texlive-extra-utils
</pre>


=== Flow chart ===
= [http://www.mono-project.com/ Mono Project] =
* LibreOffice Draw OR MS_PowerPoint (insert > shape). Check youtube.
'''Mono''' is a software platform designed to allow developers to easily create cross platform applications part of the .NET Foundation
* [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


=== Clock ===
Mono is required for [https://www.repetier.com/download-now/ Repetier-Host] software for 3D printing.
==== xclock (analog) ====
<syntaxhighlight lang='bash'>
oclock -geometry 500x500+100+0 &
</syntaxhighlight>


==== oclock (analog) ====
= NAS server =
<syntaxhighlight lang='bash'>
== OpenMediaVault ==
oclock -bg blue -geometry 500x500+100+0 -bd purple -transparent &
[[NAS#OpenMediaVault|OpenMediaVault]]
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 (digital) ====
== [http://www.freenas.org/ FreeNAS] ==
Digital clock for the X Window System with flexible display.
ZFS system (FreeBSD-based).
* http://manpages.org/dclock
* 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>
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>
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.
<pre>
dclock -date "Today is %A %B %Y" -led_off black -bg black -fg yellow -geometry 577x194+119+139 &>/dev/null &
</pre>


==== Lubuntu digital clock format ====
[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
http://netgator.blogspot.com/2012/09/change-edit-panel-digital-clock-format.html. My format is
* https://doc.freenas.org/11/vms.html
<pre>
* https://forums.freenas.org/index.php?threads/freenas-11-0-released.55327/
%a, %x, %r
* [http://www.freenas.org/blog/yes-you-can-virtualize-freenas/ Virtualize FreeNAS]
# Tue, 05/17/2016, 09:42:27 PM
* [https://wiki.freebsd.org/bhyve bhyve, the BSD Hypervisor]
* [https://forums.servethehome.com/index.php?threads/freenas-as-hypervisor-host.4888/ FreeNAS as hypervisor host]


%a %m-%d-%y, %I:%M %p
= Change detection =
# Mon 05-30-16, 08:31 AM
http://bhfsteve.blogspot.com/2013/03/monitoring-web-page-for-changes-using.html
</pre>


==== xdaliclock (digital) ====
= 3 command-line tools for feigning productivity =
https://www.mankier.com/1/xdaliclock
https://opensource.com/article/18/2/command-line-tools-productivity: [https://github.com/yaronn/blessed-contrib Blessed-contrib] (javascript), Genact, Hollywood.


Scaling is not good. Colors is changing with time.
= Mind mapping =
<syntaxhighlight lang='bash'>
* [https://www.freeplane.org/wiki/index.php/Home Freeplane]
xdaliclock -noseconds -cycle  # 'q' to quit
</syntaxhighlight>


=== Reminder take a break, relieve eye strain ===
= Diagram =
[https://github.com/hovancik/stretchly/ Stretchly]. It's open-source and cross-platform. Nodejs is required.
* [https://www.calligra.org/flow/ Calligra Flow]. Microsoft Visio alternative.


[http://www.workrave.org/ Workrave] is another choice. The source code is available too.
= Open source surveillance =
[https://www.zoneminder.com/downloads/ ZoneMinder]


[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
= Systemctl, systemd =
* Linux 系统开机启动项清理 [https://linux.cn/article-8835-1.html 中文] & [https://www.linux.com/learn/cleaning-your-linux-startup-process English]
* [https://www.tecmint.com/chkservice-manage-systemd-units-in-terminal/ Chkservice – An Easy Way to Manage Systemd Units in Terminal]
* [[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]]
* [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]
** Manage Services with Systemd
** Manage Systemd Unit Files
** Manage Sockets with Systemctl
** Systemctl Additional Commands


=== wine and winetricks ===
== Systemd vs SysVinit ==
* https://www.howtoforge.com/tutorial/how-to-use-winetricks/
* https://kernelmastery.com/systemd-vs-sysvinit/
* https://linoxide.com/linux-command/systemd-vs-sysvinit-cheatsheet/
* https://www.2daygeek.com/sysvinit-vs-systemd-cheatsheet-systemctl-command-usage/


=== Running Linux in the AWS/Amazon Web Services ===
== Systemctl vs service commands ==
* http://www.linuxuser.co.uk/tutorials/run-linux-in-the-aws-cloud
[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'''.


=== Forum software ===
<pre>
* [http://www.simplemachines.org/ Simple Machines® Forum (SMF)]. For example http://pibot.org/forum/
$ service nginx start
# VS
$ systemctl start nginx


=== RAID ===
$ systemctl  # list all services
* http://www.maximumpc.com/what-every-pc-builder-should-know-about-raid-levels/
$ cat /lib/systemd/system/rsyslog.service
 
$ systemctl status rsyslog
=== Timer ===
$ cat /lib/systemd/system/ufw.service
* 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.
 
=== How to track you laptop using Prey ===
https://www.howtoforge.com/tutorial/how-to-track-your-linux-laptop/
 
=== last command ===
[https://www.howtoforge.com/linux-last-command/ Linux last Command Tutorial for Beginners (8 Examples)]
 
==== 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>
# Works on Linux and Mac
last shutdown
last reboot
</pre>
</pre>


=== Automatic reboot after power failure ===
== How to Run a Linux Program at Startup with systemd ==
It seems there is no reliable way to find out when the power failed.
<ul>
 
<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]
The linux command 'last' can show some information about system reboot.
* Creating the Service Program for systemd to Start '''sudo nano /usr/local/bin/htg.sh''''''sudo chmod +x /usr/local/bin/htg.sh'''
 
* Creating the Service Unit File '''sudo nano /etc/systemd/system/htg.service''', '''sudo chmod 640 /etc/systemd/system/htg.service'''
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.
* Starting the Service Automatically with the systemd Command '''sudo systemctl daemon-reload''', '''sudo systemctl enable htg''', '''sudo systemctl start htg'''
 
* Verifying the Service '''sudo systemctl status htg.service'''
=== Wake up and Shut Down Linux Automatically ===
* Stopping and Disabling the Service - '''sudo systemctl stop htg.service'''
* https://help.ubuntu.com/community/WakeOnLan
<li>[https://www.makeuseof.com/create-systemd-service-on-linux/ How to Create a New systemd Service on Linux]
* https://www.cyberciti.biz/faq/ubuntu-linux-wake-on-lan-client-command-installation-examples/
</ul>
* [https://www.linux.com/learn/intro-to-linux/2017/11/wake-and-shut-down-linux-automatically 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
 
=== 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 ====
* https://fast.com/ (automatically run)
* https://www.bing.com/search?q=internet+speed+test
* http://www.speedtest.net/
 
==== Speedtest-cli ====
See [[Raspberry#Track_Internet_Dropouts|Track_Internet_Dropouts]].
 
<syntaxhighlight lang='bash'>
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
</syntaxhighlight>
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>
    /usr/local/bin/speedtest-cli --share > $log
</pre>
 
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.
 
=== '''uname''' - Print system information ===
https://www.lifewire.com/display-system-information-uname-command-3964321
 
'''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)
 
[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?]
 
=== Hardware information ===
[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]
 
==== [https://github.com/rdobson/python-hwinfo python--hwinfo] ====
https://www.2daygeek.com/python-hwinfo-check-display-system-hardware-configuration-information-linux/
 
=== Linux Logo and the current system information ===
* http://www.cyberciti.biz/hardware/howto-display-linux-logo-in-bash-terminal-using-screenfetch-linux_logo/
<syntaxhighlight lang='bash'>
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 -s  # take a screenshot and auto save it to ~/ directory.
 
odroid@odroid:~$ sudo apt-get install linuxlogo
odroid@odroid:~$ linuxlogo
        _,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
            Eight ARM  Processors, 2GB RAM, 456.00 Bogomips Total
                                    odroid
 
odroid@odroid:~$ linuxlogo -f -L list
odroid@odroid:~$ linuxlogo -f -L ubuntu
              .-.
        .-'``(|||)
    ,`\ \    `-`.                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'
        `-..-(  )
              `-`
 
 
Linux Version 3.10.96-77, Compiled #1 SMP PREEMPT Fri Feb 5 04:47:32 BRST 2016
            Eight ARM  Processors, 2GB RAM, 192.00 Bogomips Total
                                    odroid
 
odroid@odroid:~$ screenfetch -h
odroid@odroid:~$ linuxlogo -h
</syntaxhighlight>
* [https://github.com/dylanaraps/neofetch Neofetch]
 
[[File:Neofetch.png|200px]]
 
=== Dictionary - [http://artha.sourceforge.net/wiki/index.php/Home Artha] ===
* [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.
<syntaxhighlight lang='bash'>
sudo apt-get install artha
</syntaxhighlight>
 
==== Translation ====
* [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]
<syntaxhighlight lang='bash'>
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
</syntaxhighlight>


=== ASCII art/ word art ===
== How Long Does it Take To Boot Your Linux System ==
* 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]
[https://itsfoss.com/check-boot-time-linux/ Find Out How Long Does it Take To Boot Your Linux System]
* http://patorjk.com/software/taag/#p=display&f=Ivrit&t=BRR-SeqTools
<pre>
<pre>
  ____  ____  ____       ____            _____          _   
$ 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
| |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
|____/|_| \_\____/    |____/ \___|\__, ||_|\___/ \___/|_|___/
                                      |_|                   
</pre>
</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 ===
* https://www.howtoforge.com/tutorial/how-to-scan-linux-for-malware-and-rootkits/
=== Text to speech ===
* 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
=== VPN ===
* [http://lifehacker.com/the-biggest-misconceptions-about-vpns-1794038237 The Biggest Misconceptions About VPNs]
* [http://lifehacker.com/why-is-everyone-talking-about-vpns-1793768312 Why Is Everyone Talking About VPNs?]
* [http://lifehacker.com/the-laziest-cheapest-way-to-circumvent-your-snooping-i-1793789594 The Laziest, Cheapest Way to Circumvent Your Snooping ISP]
* [http://gear.lifehacker.com/the-best-vpn-service-is-private-internet-access-1794083573 Your Pick For the Best VPN Service Is Private Internet Access]
* [http://lifehacker.com/how-to-set-up-your-own-completely-free-vpn-in-the-cloud-1794302432 How to Set Up Your Own Completely Free VPN In the Cloud]
* [http://www.techhive.com/article/3158192/privacy/howand-whyyou-should-use-a-vpn-any-time-you-hop-on-the-internet.html How—and why—you should use a VPN any time you hop on the internet]
* remoteaccessvpn.nih.gov for [https://isdp.nih.gov/isdp/version.action?prodid=140 NIH]. Download and unzip the profile and place the profile (.xml)in “/opt/cisco/anyconnect/profile/” directory
==== OpenVPN ====
* [https://nordvpn.com/tutorials/linux/openvpn/ Tutorial from nordvpn] (free 3-day trial)
* [https://www.digitalocean.com/community/tutorials/how-to-set-up-an-openvpn-server-on-ubuntu-14-04 How To Set Up an OpenVPN Server on Ubuntu 14.04]
* [https://youtu.be/XDCv_xw4BW4 How to Build An OpenVPN Access Point] by Hak5 in Youtube.
* [https://www.howtoforge.com/tutorial/openvpn-secure-server-administration/ Secure you server administration with multiplatform VPN connection] by howtoforge.
==== List of free and fast VPNs ====
* [https://www.makeuseof.com/tag/best-free-vpn-for-linux/ The 7 Best VPNs for Linux] Oct 2018
* [http://www.makeuseof.com/tag/5-great-free-vpn-services-compared-which-is-fastest/ 5 Great Free VPN Services Compared: Which Is Fastest?]
* [https://www.howtogeek.com/342330/how-to-choose-the-best-and-fastest-alternative-dns-server/ How to Choose the Best (and Fastest) Alternative DNS Server]
* [https://windscribe.com/ Windscribe], mentioned by [https://www.techhive.com/article/3105577/streaming-media/tired-of-nbcs-olympics-coverage-operas-free-unlimited-vpn-is-the-way-to-go.html Sick of NBC's vapid Olympics coverage? Use a VPN and you can watch the BBC's coverage instead]
* Some result from one slickdeals comment:
** my connection speed is 150 down, when i do a speed test i get 170 down.
** with nordvpn trial i get 165 down
** with windscribe free i get 95 down
** with vpnsecure trial i get 30 down
==== How to Set Up a VPN on Your Router ====
https://www.makeuseof.com/tag/setup-vpn-router/
=== [http://www.mono-project.com/ 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 [https://www.repetier.com/download-now/ Repetier-Host] software for 3D printing.


=== NAS server ===
== Check if Your Linux System Uses systemd ==
==== [http://www.openmediavault.org/ OpenMediaVault] ====
[https://itsfoss.com/check-if-systemd/ How to Check if Your Linux System Uses systemd]
[http://www.pcworld.com/article/3150765/linux/4-easy-linux-projects-for-newbies-and-intermediate-users.html 4 easy Linux projects for newbies and intermediate users]. OpenMediaVault is a linux-based system.


[https://github.com/ikogan/docker-openmediavault Docker container for OpenMediaVault]. [http://www.songming.me/docker.html OpenMediaVault插件之Docker教程]
== chkservice ==
[https://www.linuxuprising.com/2019/11/chkservice-is-systemd-units-manager.html chkservice] Is A systemd Unit Manager With A Terminal User Interface


==== [http://www.freenas.org/ FreeNAS] ====
= Kernel =
ZFS system (FreeBSD-based).
* [https://opensource.com/article/19/8/linux-kernel-21st-century How to compile a Linux kernel in the 21st century]
* [https://www.ostechnix.com/different-ways-to-update-linux-kernel-for-ubuntu/ Different Ways To Update Linux Kernel For Ubuntu]


[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
= Firmware update =
* https://doc.freenas.org/11/vms.html
[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]
* https://forums.freenas.org/index.php?threads/freenas-11-0-released.55327/
* [http://www.freenas.org/blog/yes-you-can-virtualize-freenas/ Virtualize FreeNAS]
* [https://wiki.freebsd.org/bhyve bhyve, the BSD Hypervisor]
* [https://forums.servethehome.com/index.php?threads/freenas-as-hypervisor-host.4888/ FreeNAS as hypervisor host]


=== Change detection ===
= Game =
http://bhfsteve.blogspot.com/2013/03/monitoring-web-page-for-changes-using.html
See [[Game|Game]].


=== 3 command-line tools for feigning productivity ===
= Best Linux Adobe Alternatives You Need to Know =
https://opensource.com/article/18/2/command-line-tools-productivity: [https://github.com/yaronn/blessed-contrib Blessed-contrib] (javascript), Genact, Hollywood.
 
=== Mind mapping ===
* [https://www.freeplane.org/wiki/index.php/Home Freeplane]
 
=== Diagram ===
* [https://www.calligra.org/flow/ Calligra Flow]. Microsoft Visio alternative.
 
=== Open source surveillance ===
[https://www.zoneminder.com/downloads/ ZoneMinder]
 
=== Systemctl, systemd ===
* Linux 系统开机启动项清理 [https://linux.cn/article-8835-1.html 中文] & [https://www.linux.com/learn/cleaning-your-linux-startup-process English]
* [https://www.tecmint.com/chkservice-manage-systemd-units-in-terminal/ Chkservice – An Easy Way to Manage Systemd Units in Terminal]
 
=== Bitcoin ===
* [https://www.makeuseof.com/tag/mine-bitcoin-linux/ Mine Bitcoin on Linux With These Best Free Apps]
* [https://www.howtogeek.com/347210/how-to-buy-bitcoin-the-easy-way/ How to Buy Bitcoin the Easy Way]
 
=== Check weather ===
* [https://www.linuxuprising.com/2018/07/display-weather-forecast-in-your.html Display Weather Forecast In Your Terminal With Wttr.in] <syntaxhighlight lang='bash'>
$ curl wttr.in
$ curl wttr.in/washington
$ curl wttr.in/olney
$ curl wttr.in/~olney
$ curl wttr.in/taipei
</syntaxhighlight>
* [https://www.makeuseof.com/tag/check-weather-linux-desktop/ 10 Ways to Check the Weather From Your Linux Desktop]
 
=== Game ===
* [https://itsfoss.com/download-linux-games/ Fantastic Linux Games and Where to Find Them]
* [https://www.makeuseof.com/tag/best-linux-games/ The 10 Best Linux Games You Can Play for Free] (2019)
 
=== Best Linux Adobe Alternatives You Need to Know ===
* https://linux.cn/article-8928-1.html and https://www.maketecheasier.com/adobe-alternatives-for-linux/
* https://linux.cn/article-8928-1.html and https://www.maketecheasier.com/adobe-alternatives-for-linux/


=== Linux distributions ===
= Linux distributions =
[https://www.fossmint.com/linux-distros-you-never-heard-about/ The Top 10 Open Source Distros You Haven’t Heard About]
[[Linux_Distribution|Linux Distribution]]
 
==== Popular Linux distributions ====
[https://www.ithome.com.tw/news/121357 2017年度最佳Linux版本出爐], https://www.linuxquestions.org/questions/linux-news-59/2017-linuxquestions-org-members-choice-award-winners-4175623289/
 
==== Small/lightweight Linux distributions ====
* [http://www.makeuseof.com/tag/linux-distro-space/ Install Linux to Save Space! These Tiny Linux Distros Are Super Small] 10/10/2017
* [https://www.makeuseof.com/tag/6-lightweight-linux-distributions-give-pc-lease-life/ 13 Lightweight Linux Distributions to Give Your Old PC a New Lease of Life] 5/5/2017. Some distributions that can be run in RAM: Macpup, Porteus.
 
==== 10 Best And Most Secure Linux Distributions ====
https://fossbytes.com/secure-linux-distros-privacy-anonymity/


==== Kids ====
= chroot =
[https://www.maketecheasier.com/configure-linux-for-children/ How to Configure Linux for Children]
[[Chroot|Chroot]]

Revision as of 21:38, 27 April 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

export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'

(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

How to Free Up Memory and Improve RAM Performance on Linux

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

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

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 {} +

find . -exec grep chrome {} \;
# or
find . -exec grep chrome {} +

find will execute grep and will substitute {} with the filename(s) found. The difference between ; and + is that with ; a single grep command for each file is executed whereas with + as many files as possible are given as parameters to grep at once. The backslash before ; is to escape ; so linux won't interpret it directly.

  • 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 {} + 

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.

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
    

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)

All You Need To Know About Processes in Linux

http://www.tecmint.com/linux-process-management/

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 - non-critical files. 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

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

finger: show user information

finger USERNAME

List all user groups

How to List All User Groups on Linux

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

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)

# Find the up network adaptors
$ nmcli dev status
DEVICE           TYPE      STATE        CONNECTION         
docker0          bridge    connected    docker0            
eno1             ethernet  connected    Wired connection 1 

# Find the DNS 
$ nmcli dev show | grep 'IP4.DNS'

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 ss -lnt

sudo ss -tulpn | grep LISTEN

contain pid,

add "sudo" can show program/command names on the last column

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.
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.

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?

# 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

  ____  ____  ____       ____            _____           _     
 | __ )|  _ \| __ )     / ___|  ___  __ |_   _|__   ___ | |___ 
 |  _ \| |_) |  _ \ ____\___ \ / _ \/ _` || |/ _ \ / _ \| / __|
 | |_) |  _ <| |_) |_____|__) |  __/ (_| || | (_) | (_) | \__ \
 |____/|_| \_\____/     |____/ \___|\__, ||_|\___/ \___/|_|___/
                                       |_|                     
  ____  _____  ____        _____         _______          _     
 |  _ \|  __ \|  _ \      / ____|       |__   __|        | |    
 | |_) | |__) | |_) |____| (___   ___  __ _| | ___   ___ | |___ 
 |  _ <|  _  /|  _ <______\___ \ / _ \/ _` | |/ _ \ / _ \| / __|
 | |_) | | \ \| |_) |     ____) |  __/ (_| | | (_) | (_) | \__ \
 |____/|_|  \_\____/     |_____/ \___|\__, |_|\___/ \___/|_|___/
                                         | |                    
                                         |_|                    
  ___ ___ ___     ___          _____         _    
 | _ ) _ \ _ )___/ __| ___ __ |_   _|__  ___| |___
 | _ \   / _ \___\__ \/ -_) _` || |/ _ \/ _ \ (_-<
 |___/_|_\___/   |___/\___\__, ||_|\___/\___/_/__/
                             |_|                  

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 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
    • Creating the Service Unit File sudo nano /etc/systemd/system/htg.service, sudo chmod 640 /etc/systemd/system/htg.service
    • Starting the Service Automatically with the systemd Command sudo systemctl daemon-reload, sudo systemctl enable htg, sudo systemctl start htg
    • Verifying the Service sudo systemctl status htg.service
    • Stopping and Disabling the Service - sudo systemctl stop htg.service
  • How to Create a New systemd Service on Linux

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