More Bash

Here are some more, hopefully useful hacks for bash scripts.

Default options

It is often recommended to set a few options in bash scripts as default:

set -euo pipefail

What that means:

  • -e : Immediately exit the bash script if a command fails.
  • -u : Immediately exit the bash script if an undefined variable is called.
  • -o pipefail : In case of chained (“piped”) command (e. g. grep something /var/log/something.log | sort) fails, return the error code of the failed command for the chain/pipe.

This is sometimes also referred to as unofficial “Bash strict mode”. But it comes with caveats!

Redirect output

# Disable stderr
exec 2>/dev/null

# Disable stdout
exec 1>/dev/null

# Disable both
exec 2>&1 1>/dev/null

# Redirect all output to some kind of log file
exec 1> /tmp/output.log
exec 2>&1

The internal field separator (IFS)

This variable defines how the bash splits strings. Useful when used in combination with read, for example:

IFS='|' read key value <<< "someKey|someValue"; echo "key: $key; value: $value"

Default values

# If nothing is provided as first argument, use someFile.txt as filename
filename=${1:-someFile.txt}

Multiline text snippets

cat << EOF
This is some
input over
multiple lines
EOF
mail -s "Alarm!" admin@example.com << EOF
Someone tried to hack your server!
Kind Regards,
The friendly hacker
EOF

Note: EOF is just some marker, you can call it whatever you want. EOF (end of file) or EOT (end of transmission) is often used.