bash script

bash: exit

exit N

Exit with the status code N.

echo $?

echo the last command's exit code.



Special care must be taken when using pipes.
By default, the return value of a command is that of the last command in the pipe chain.
If one wants to capture an error return value, one may use set -o pipefail:
"pipefail: the return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status."

set -o pipefail

bash: declare

Documented in the 'SHELL BUILTIN COMMANDS' section of man bash or here:


function assign {
  # -g makes the variable global.
  declare -g $1=$2

assign my_var 42
echo $my_var

bash: arrays

Associative arrays:

# Local:
declare -A my_array
# Global:
declare -gA my_array

declare -A my_array=( ['']='empty' [0]='zero' ['a']='letter' )

# Add item to the array

# Iterate over array:
for i in "${my_array[@]}"
        echo $i

Array indirection

Use a temporary variable to allow for array addressing indirection.

# $1 = 'my_array
declare -gA $1 # Declare array
# $1+=('banana'='fruit') # Will not work!
var+=('banana'='fruit') # Ok. Adds an element to the array.

bash: let

Documented in the 'SHELL BUILTIN COMMANDS' section of man bash or here:


# The following will not work because the script will try to run the non-existing command 'configuration_file'
# $loaded=1
# However, this works:
let $loaded=1

For an alphanumeric string, use declare:

  # -g makes the variable global.
  declare -g $1=$2


Bash: builtin commands

Documented in the 'SHELL BUILTIN COMMANDS' section of man bash or here:

Bash: saving settings to file


# Create variable
# Save variable to file:
echo 'VERSION="'"$VERSION"'"' >> .variables

# Source file to load variables:
. .variable
echo "$VERSION"
# Increment:
echo "$VERSION"
# Delete previous value from file:
sed --in-place  '/^VERSION=/d' ./.variables
# Save new value:
echo 'VERSION="'"$VERSION"'"' >> .variables
# Note that the above, simple implementation will append a new line to .variables each time the value is saved. $VERSION will still evaluate to the last value saved, though.

What you must know before you start bash scripting


By understanding the following few gotchas, you can save yourself some hair pulling and hours of frustration. There are a few things that you must be aware of, as your read documentation, tutorials and code examples.

Spaces are significant: Beware of the existence or absence of an extra space before and after such characters as =, ;, [, ], {, }. The space is significant. Not respecting its use will break code snippets you may be learning from.

# Wrong variable declaration
myvar = "Hello"
# Right:

Syndicate content