Miscellaneous

Optional arguments

args=("$@")
args+=(foo)
args+=(bar)
echo "${args[@]}"

Put the arguments into an array and then append

Strict mode

set -euo pipefail
IFS=$'\n\t'

See: Unofficial bash strict mode

Conditional execution

git commit && git push
git commit || echo "Commit failed"

Reading input

echo -n "Proceed? [y/n]: "
read ans
echo $ans
read -n 1 ans    # Just one character

Go to previous directory

pwd # /home/user/foo
cd bar/
pwd # /home/user/foo/bar
cd -
pwd # /home/user/foo

Heredoc

cat <<END
hello world
END

Backslash escapes

  • Â
  • !
  • "
  • #
  • &
  • '
  • (
  • )
  • ,
  • ;
  • <
  • >
  • [
  • |
  • \
  • ]
  • ^
  • {
  • }
  • `
  • $
  • *
  • ? Escape these special characters with \

Grep check

if grep -q 'foo' ~/.bash_history; then
    echo "You appear to have typed 'foo' in the past"
fi

Special variables

Expression Description
$? Exit status of last task
$! PID of last background task
$$ PID of shell
$0 Filename of the shell script
See Special parameters.

Check for command's result

if ping -c 1 google.com; then
    echo "It appears you have a working internet connection"
fi

Getting options

while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
    -V | --version )
    echo $version
    exit
    ;;
    -s | --string )
    shift; string=$1
    ;;
    -f | --flag )
    flag=1
    ;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi

printf

printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga
printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"
printf "Print a float: %f" 2
#=> "Print a float: 2.000000"

Trap errors

trap 'echo Error at about $LINENO' ERR

or

traperr() {
    echo "ERROR: ${BASH\_SOURCE[1]} at about ${BASH\_LINENO[0]}"
}
set -o errtrace
trap traperr ERR

Case/switch

case "$1" in
    start | up)
    vagrant up
    ;;
    *)
    echo "Usage: $0 {start|stop|ssh}"
    ;;
esac

Directory of script

DIR="${0%/\*}"

Source relative

source "${0%/\*}/../share/foo.sh"

Redirection

python hello.py > output.txt   # stdout to (file)
python hello.py >> output.txt  # stdout to (file), append
python hello.py 2> error.log   # stderr to (file)
python hello.py 2>&1           # stderr to stdout
python hello.py 2>/dev/null    # stderr to (null)
python hello.py &>/dev/null    # stdout and stderr to (null)
python hello.py < foo.txt      # feed foo.txt to stdin for python

Inspecting commands

command -V cd
#=> "cd is a function/alias/whatever"

Subshells

(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory

Numeric calculations

$((a + 200))      # Add 200 to $a
$(($RANDOM%200))  # Random number 0..199
Comments