Contents: Bash Reference Sheet

TableOfContents

Basic Structures

Compound Commands

Compound commands are statements that can execute several commands but are considdered as a sort of command group by Bash.

Command Lists

Expressions

Loops

Builtins

Builtins are commands that perform a certain function that has been compiled into Bash. Understandably, they are also the only types of commands (other than those above) that can modify the Bash shell's environment.

Dummies

Declarative

Input

Output

Execution

Jobs/Processes

Conditionals And Loops

Arguments

Tests

Exit Codes

An Exit Code or Exit Status is an unsigned 8-bit integer returned by a command that indicates how its execution went. It is agreed that an Exit Code of 0 indicates the command was successful at what it was supposed to do. Any other Exit Code indicates that something went wrong. Applications can choose for themselves what number indicates what went wrong; so refer to the manual of the application to find out what the application's Exit Code means.

Testing The Exit Code

Patterns

Bash knows two types of patterns. Glob Patterns is the most important, most used and best readable one. Later versions of Bash also support the "trendy" Regular Expressions. It is however ill-adviced to use regular expressions in scripts unless you have absolutely no other choice or its use greatly outweighs the use of globs in advantages. Generally speaking, if you need a regular expression, you'll be using awk(1), sed(1), or grep(1) instead of Bash.

Glob Syntax

Testing Patterns

Parameters

Parameters are what Bash uses to store your script data in. There are Special Parameters and Variables.

Any parameters you create will be variables, since special parameters are read-only parameters managed by Bash. It is recommended you use lower-case names for your own parameters so as not to confuse them with the all-uppercase variable names used by Bash internal variables and environment variables. It is also recommended you use clear and transparent names for your variables. Avoid x, i, t, tmp, foo, etc. Instead, use the variable name to describe the kind of data the variable is supposed to hold.

It is also important that you understand the need for quoting. Generally speaking, whenever you use a parameter, you should quote it: echo "The file is in: $filePath". If you don't, bash will tear the contents of your parameter to bits, delete all the whitespace from it, and feed the bits as arguments to the command. Yes, Bash mutilates your parameter expansions by default - it's called Word Splitting - so use quotes to prevent this. BRThe exception is keywords and assignment. After myvar= and inside [[', case, etc, you don't need the quotes, but they won't do any harm either - so if you're unsure: quote!

Last but not least; remember that parameters are the data structures of bash. They hold your application data. They should NOT be used to hold your application logic. So while many ill-written scripts out there may use things like GREP=/usr/bin/grep, or command='mplayer -vo x11 -ao alsa', you should NOT do this. The main reason is because you cannot possibly do it completely right and safe and readable/maintanable. BRIf you want to avoid retyping the same command multiple times, or make a single place to manage the command's command line, use a function instead. Not parameters.

Special Parameters

Examples: Basic Structures

Compound Commands

Command Lists

  • [[ $1 ]] || { echo "You need to specify an argument!" >&2; exit 1; }

    • We use a command group here because the || operator takes just one command. BRWe want both the echo and exit commands to run if $1 is empty.

  • (IFS=','; echo "The array contains these elements: ${array[*]}")

    • We use paranthesis to trigger a subshell here. BRWhen we set the IFS variable, it will only change in the subshell and not in our main script. That avoids us having to reset it to it's default after the expansion in the echo statement (which otherwise we would have to do in order to avoid unexpected behaviour later on).

  • (cd "$1"; tar -cvjpf archive.tbz2 .)

    • Here we use the subshell to temporarily change the current directory to what's in $1. BRAfter the tar operation (when the subshell ends), we're back to where we were before the cd command because the current directory of the main script never changed.

Expressions

  • ((completion = current * 100 / total))

    • Note that arithmetic context follows completely different parsing rules than normal bash statements.

  • [[ $foo = /* ]] && echo "foo contains an absolute pathname."

    • We can use the [[ command to perform all tests that test(1) can do. BRBut as shown in the example it can do far more than test(1); such as glob pattern matching, regular expression matching, test grouping, etc.

Loops

Builtins

Dummies

  • while true; do ssh lhunath@lyndir.com; done

    • Reconnect on failure.

Declarative

  • alias l='ls -al'

  • declare -i myNumber=5

  • export AUTOSSH_PORT=0

  • foo() { local bar=fooBar; echo "Inside foo(), bar is $bar"; }; echo "Setting bar to 'normalBar'"; bar=normalBar; foo; echo "Outside foo(), bar is $bar"

  • if ! type -P ssh >/dev/null; then echo "Please install OpenSSH." >&2; exit 1; fi

Input

  • read firstName lastName phoneNumber address

Output

  • echo "I really don't like $nick.  He can be such a prick."

  • printf "I really don't like %s.  He can be such a prick." "$nick"

Execution

  • cd ~lhunath

  • command [ $a = a ] || echo "$a is not 'a'!"

  • source bashlib; source ~/.foorc

  • exec 2>/var/log/foo.log

  • echo "Fatal error occurred!  Terminating!"; exit 1