bash cheat sheet

💻 IO Redirect

💻 File condition tests

if [[ -f filename ]]; then
  # file exists
else
  # file not exists
fi
# OR
[ -f ~/dotfiles/.bashrc ] && source ~/dotfiles/.bashrc

💻 check last command status code

if test $? = 0; then
  echo 'do this';
else
  echo 'do that';
fi

💻 Variable condition tests

if [[ -z $? ]]; then
  # last command run successfully
  echo "status code is 0"
else
  echo "status code is not null, something wrong"
fi
 
[ -z "$ENV_VAR" ] && echo "ENV_VAR is empty"
[[ ! -z "$ENV_VAR" ]] && echo "ENV_VAR is not empty" || echo "ENV_VAR is empty"

💻 numberic conditionals

💻 check if command available

if !type brew &>/dev/null; then
  echo "brew install"
fi
# or
if which brew &>/dev/null; then
  echo 'brew installed'
fi
# or
if command -v brew &> /dev/null; then
    echo "brew install"
fi

💻 Manipulating and/or expanding variables

parameter substitution

If parameter not set, use default
${parameter-default}, ${parameter:-default}
If parameter not set, set it to default
${parameter=default}, ${parameter:=default}
If parameter set, use alt_value, else use null string
${parameter+alt_value}, ${parameter:+alt_value}
If parameter set, use it, else print err_msg and abort the script with an exit status of 1
${parameter?err_msg}, ${parameter:?err_msg}

💻 Shortcuts

💻 For

for name [in list]
do
  [statements that can use $name]
done

💻 Case

case expression in
  pattern1 )
    statements ;;
  pattern2 )
    statements ;;
esac

💻 $() vs backtick

ref

The backticks/gravemarks have been deprecated in favor of $() for command substitution.

💻 Special bash variables

ref

The implementation of $* has always been a problem and realistically should have been replaced with the behavior of $@. In almost every case where coders use $*, they mean $@. $* Can cause bugs and even security holes in your software.
find . -iname "*filename*"
find . -type d