General Command line commands

Useful command line commands

Manipulating standard out

# show all except first line of a file
cat $file | tail -n+2

# show all except last row of a file
cat $file | head -n -1

# show only first three rows
cat $file | head -3

# show only last three rows
cat $file | tail -3

# display recent changes log file
tail -f $file

# Remove pattern at beginning of variable
"${var#http://}"
# Remove pattern at end of variable
"${var%/score/}"

File comparison

# Compare 2 files and output only overlapping rows
diff -u a.txt b.txt | grep -v ^- | grep -v ^+ | grep -v ^@

String functions

# Remove line separator and tab separate every other line 
cat $file | paste - -

Command line menu

#!/bin/bash
# Ask user for numeric input. Invalid input will result in new request user input. Valid
PS3='Please enter choice: '
options=("Option 1" "Option 2" "Option N")
select opt in "${options[@]}"
do
 case $opt in
        "Option 1")
                ./do_route1.sh
                break
                ;;

        "Option 2")
                ./do_route2.sh
                break
                ;;
        "Option N")
        		./do_routeN.sh
        		break
        		;;
        *) echo invalid option ;;
 esac

Command line arg parsing shifting the pointer


while true; do
  case "$1" in
    -h | --help       ) help ;;
    --version         ) echo "Version: ${VERSION}"; exit ;;
    --user            ) USER_ID="$2"          ; shift 2 ;;
    --isTest       ) TEST="true"        ; shift   ;;
    --grp     ) GRP_ID="$2"      ; shift 2 ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done