Redirections

Suppress output and errors

$ hello-world
Hello World!
$ hello-world >/dev/null 2>&1

Read first line of a file into a variable

To put the first line of the file /etc/sympa/cookie into the variable $COOKIE use the read builtin:

$ read -r COOKIE < /etc/sympa/cookie

Determine source directory of a bash script

A bash script that tries to access a file with a relative path to the source directory will fail when the script is called from another directory.

In this case you can determine the absolute path with the $BASH_SOURCE variable:

FILE=$(dirname "${BASH_SOURCE[0]}")/myfile.txt

Verify environment variable

Check that environment variable API_USER is present and not empty:

: "${API_USER:?Please set API_USER environment variable}"

Substitutions

Default value for first command line parameter:

DATE=${1:2019-January}

The substitution can be any shell syntax, even a command:

DATE=${1:-`date +"%Y-%B"`}

Check syntax of shell script

$ bash -n myscript

History

Resources

How To Use Bash History Commands and Expansions