Begin Linux

Bash essentials: the 20 commands you will use every day

You do not need hundreds of commands to be useful. You need twenty, and the habit of reading what they print.

Where am I, what is here

pwd            # print working directory
ls -la         # list everything, long format, including dotfiles
cd /var/log    # change directory (cd alone returns home, cd - goes back)
tree -L 2      # if installed: directory tree, two levels deep

Reading files

cat /etc/os-release        # print a whole file
less /var/log/syslog       # page through a file; q quits, / searches
head -n 20 file.log        # first 20 lines
tail -f /var/log/auth.log  # follow a file as it grows (Ctrl-C to stop)
grep -i "error" file.log   # lines containing "error", case-insensitive
grep -rn "ServerName" /etc/apache2/   # recursive, with line numbers

Changing things

cp -a source dest          # copy, preserving permissions and timestamps
mv old new                 # move or rename
mkdir -p a/b/c             # create nested directories
rm -i file                 # remove, asking first; never alias rm to -rf
nano file.conf             # simple editor; Ctrl-O save, Ctrl-X exit

Finding and measuring

find /var -name "*.log" -mtime -1     # logs modified in the last day
du -sh /var/*                         # size of each directory
df -h                                 # free space per filesystem
ps aux | grep nginx                   # running processes matching nginx
top                                   # live view of CPU and memory (q quits)

Three habits that matter more than any command

  1. Read the output. Most “it did not work” questions are answered in the line you scrolled past.
  2. Use --help and man. man ls is faster than a search engine once you are used to it.
  3. Tab completion. Type the first letters and press Tab. It also prevents typos in paths.
Exercise: on a fresh virtual machine, find the five largest directories under /var, then find which process writes to the largest log file. Write down the commands you used.