Bash Scripting Cheat sheet

Printing

  • echo "my simple output"
  • echo -e "interpret \b backslash \n escapes
  • echo -n "output without trailing new line"
  • printf "String: %s\nDecimal: %d\nHex: %x\nOctal: %o\n" Hello 100 100 100    
    String: Hello
    Decimal: 100
    Hex: 64
    Octal: 144
    

Variables

  • storing: location="hello"
  • accessing: "${location}"

Comparison

  • if [ "$x" = "valid" ]; then
      echo "x has the value 'valid'"
    else
    echo "x does not have the value 'valid'"
    fi
    
  • [ "$x" = "valid" ] && echo "x has the value 'valid'"
    
    [ "$x" = "valid" ] || { echo invalid && false }  && echo "valid"
    
  • grep -i $name ~uli101/uli101/phonebook
    
    if [ "$?" != "0" ]
      then echo -n "Name '$name' not in directory "
    fi