Shell scripting

  • passing arguments
  • if-else, case
  • loops
  • string, numbers, arrays
  • functions, local variables
  • expressions and operators
  • testing, debugging
  • process substitution
  • traps
  • wait eval, named pipes

Shebang

  • Always use specific shell instead if generic /bin/sh symlink
    • since it can point to any shell
#/bin/bash
  • use /usr/bin/env for maximum portability
    • since shell executables can be at other place in different OS like FreeBSD
    • This searches shell binary in PATH
#/usr/bin/env bash

Make script executable

# just make it executable
chmod +x script.sh
 
# make it executable for all users
# nobody except you can change the code
chmod 755 script.sh
 
# make it executable for current user only
chmod 700 script.sh

Script file location

  • System wide
    • /usr/local/bin
  • Single user
    • ~/bin
    • ~/.local/bin

check if a file exists

if [ -e "db/restore-db.sh" ]; then
  echo "Yes"
else
  echo "No"
fi