BASH Scripting
bash
supports many features available in traditional programming languages. However, since bash
is a shell first, and programming language second, there are a few quirks that you need to be aware of. This page covers several topics that are useful when writing bash scripts and provides examples.
variables
Bash supports several "programming" concepts, including variables. However, the syntax for using variables in bash can seem a little strange. When setting variables, use only the variable name
and make sure there is not a space between the variable name and the equal sign. When deferencing a variable, put the variable name in ${}
. Variable substitution will be performed inside of double
quotes, but not inside of single quotes. Here is an example:
#! /bin/bash
msg="hello world"
echo "i am supposed to give you this message: ${msg}" # will print: i am supposed to give you this message: hello world
echo 'i am supposed to give you this message: ${msg}' # will print: i am supposed to give you this message: ${msg}
echo "i am supposed to give you this message: '${msg}'" # will print: i am supposed to give you this message: 'hello world'
echo "i am supposed to give you this message: \"${msg}\"" # will print" i am supposed to give you this message: "hello world"
The shell automatically sets several special variables. These special variables <code>${1}, ${2}, ...<code> contain the arguments that were given to your script.
<code> #! /bin/bash echo "arg 1: $1" echo "arg 2: $2" echo "arg 3: $3" echo "not sure about the rest"
conditionals (if
statements)
Bash also supports running code "conditionally". This is useful for checking that the correct number of arguments where given to your script, or