Bash Tricks

Mort Yao

Use a variable, abort if it has an empty value

${str?-WTF!}

Get the substring

${str:0:1}

Test if a string starts with some string

if [[ $str == /* ]]; then
  ...
fi

Test if a string matches some regular expression

if [[ $str =~ ^/ ]]; then
  ...
fi

Combining expressions in if-statements

if [[ expr1 && expr2 || expr3 ]]; then
  ...
fi

Read a file line by line

while IFS= read -r line; do
  echo $line
  ...
done

To strip preceding spaces (indentation), use:

while read -r line; do
  echo $line
  ...
done