Category Archives: SHELL

A random assortment of helpful shell commands/scripts.

“It lies in the power of every man, either permissively to hasten, or actively to shorten, but not to lengthen or extend the limits of his natural life. He only (if any) hath the art to lengthen his taper, that put it to best advantage.”
Francis Quarles

Here are some nifty command line scripts which come in handy:

  1. Show the lines in a file which are uncommented and not empty
    grep -E -v “#|^$” file
    or alternatively (just to use sed)
    grep -E -v “#” | sed ‘/^$/d’
  2. Create 10 txt files
    touch test{0..9}.txt
  3. Move all txt files to bak files
    for i in *txt
    do
    j=`echo $i | sed ‘s/txt/bak/’`
    mv $i $j
    done
  4. Find out who is using the most disk space
    du -hs /home/* | sort -n
  5. Selecting the most recent file in a directory
    ls -rt | tail -1
  6. Excluding the grep command from ps aux
    Lets say you want to grep the process list for all vi processes. The resulting list  will contain the grep command itself. To avoid this use
    ps aux | grep [v]i
  7. Compare the differences between a remote & local file
    ssh user@server cat remote.txt | diff -y local.txt –
  8. Quickly create a dated backup
    Firstly create an alias in your .bashrc
    echo “alias d=’date +%F” >> .bashrc
    Restart your terminal & try
    mv file.txt{,.$(d)}
  9. Quickly remove all whitespace
    cat file.txt | sed ‘s/\s\+//g’
  10. Columnize output
    column -s : -t /etc/passwd
    would format passwd in columns using : as a delimiter.
  11. Get the total weight of certain files in a directory
    du -hc *txt
    or
    ls -al *txt | awk ‘{ print; total += } END { print total / 1.024e+9 }’
  12. Count any number of lines before or after a search match
    egrep -A 15 test testytest.txt
    Provides the next 15 lines after the match.
    egrep -B 15 test testytest.txt
    Provides the 15 lines before the match.
  13. List services running on a machine
    netstat -nptl | egrep ‘^tcp’ | awk ‘{if($7!=”-“){print $7}}’ | cut -d/ \ -f2 | sort -u
  14. How much RAM does a machine have?
    egrep ‘MemTotal’ /proc/meminfo | awk ‘{print $2/1024, “MB”}’
  15. How many disks does a machine have?
    fdisk -l 2>/dev/null | egrep ‘/dev/(s|xv)d[a-z]:’ | \
    awk ‘{count++}END{print count}’

Public Domain Mark