bash Scripting - robbiehume/CS-Notes GitHub Wiki

Links

General notes

Specific notes

  • shift: discards the first positional parameter (``) and moves all the remaining parameters one position to the left

  • Exit if error occurs: set -e

  • Output:

    • Can do echo -e or printf to interpret newline characters (\n)
  • Variable

    • Can do: my name is $NAME_VAR or my name is ${NAME_VAR}
  • Increment number variable

    • ((num++)) Built-in variables
    • $@ //all command line arguments
    • $# // number of command line arguments
  • Print array values

    • echo ${arr[0]}
  • User input

    • read -p "Enter your name: " NAME
      • Input is stored to NAME variable
    • Multiple input:
      • read name1 name2
        • Stores first entered name as name1 and second as name2
  • If statement

    • if [ "$NAME" == "Robbie" ]
      then
          echo "Your name is Robbie"
      elif [ "$NAME" == "Jack" ]
      then
          echo "Your name is Jack"
      else
          echo "Your name is NOT Robbie or Jack"
      fi
      
  • Integer Comparison

    • Equal/NOT equal: -eq / -ne
    • Greater (Less) than: -gt / -lt
    • Greater (Less) than or equal to: -ge / -le
  • String comparison:

    • Equal: = or ==
    • NOT Equal: !=
    • Check if string is null (zero length): -z
  • File Condition Flags

    • For the following flags:
      • -e : true if file exists
      • -f : true if file exists and is a regular file
      • -d : true if file exists and is a directory
      • -s : true if the file has non-zero size
  • Case statement

    • read - p 'Are you 21 or over? Y/N "  ANSWER
      case "$ANSWER" in 
          [yY] | [yY][eE][sS])
              echo 'You can have a beer :)'
              ;;
          [nN] | [nN][oO])
              echo 'Sorry, no drinking'
              ;;
          *)
              echo 'Please enter y/yes or n/no'
              ;;
      Esac
      
  • For loop

    • FILES=$(ls *.txt)
      for FILE in $FILES
          do 
          echo "Renaming $FILE to new-$FILE"
          mv $FILE $NEW-$FILE
      done
      
  • While loop

    • LINE=1
      while read -r CURRENT_LINE
          do
          echo "$LINE: $CURRENT_LINE"
          ((LINE++))
      done < "./file.txt"
      
  • Function

    • function sayHello() {   # can also do it without the function keyword
          echo "Hello World, my name is $1"
      }
        
      sayHello "Robbie"
      

String manipulation

  • Uppercase first letter: "${str_var^}"
  • All uppercase: "${str_var^^}"
  • All lowercase: "${str_var,,}"

Misc.

  • Dynamic variable names: link
    • stg_release=1.0
      env=stg
      declare -n env_release="${env}_release"
      echo $env_release ${!env_release}  // outputs: 1.0 stg_release
      
  • Evaluating variables in a string: link
  • Understanding backtick: link
  • eval command: link
  • Replace (first) occurrences of a string: link
  • Get user input (and confirm?): link

Commands for specific scenarios

  • Run command as root with login environment: sudo bash -lc "<command>"
  • Run command as different user sudo -u <user>
  • Run a bash script with current environment (link): . <script_name>
  • Get absolute path to parent directory of running script: dirname "$(realpath $0)"
  • Get last argument passed to function or script (link): ${@: -1} or for last; do true; done //value will be in $last
  • Check if variable is one of multiple values:
    • acceptable_values=("value1" "value2" "value3")
      if [[ " ${acceptable_values[@]} " =~ " ${my_var} " ]]; then 
      ...
⚠️ **GitHub.com Fallback** ⚠️