Shell Scripting

Variable Setting

variable=1 # no spaces allowed

If Statements

If statements go like this:

if []; then

elif []; then #optional

else #optional

fi

Testing

test in unix is a command that evaluates conditional expressions.

In shell we can write these implicitly within an if statement like such:

if [ statement = answer ]; then

But the spaces between the brackets and the expression are super important. It won't work otherwise.

Loops

Loops in Shell work essentially as in anything else. There's while and for, and to start and end them we need do and done.

e.g.

while read input
do
...
done

Default Variables

  • $# = number of arguments
  • $0 = program number
  • $n (e.g. $1, $2, etc) = the nth argument
  • $@ = all arguments in one go
  • $* = all arguments as separate things (like for i in $*)

Backticks (`)

Backticks enable us to execute a command and pass the value back in to a variable, rather than literally setting the variable to be the command.

e.g. "a=`echo hello world | wc`" will place the word count into a.

Read

Reading in input is done by saying:

read blah

This will assign the line of input to $blah. If we say:
read x y z

This will split it up by spaces into $x, $y and the remainder $z.

E.g.

read x y z
echo $x
echo $y
echo $z

Run with:

.blah.sh
hello world this is me

Will output:
hello
world
this is me

Arrays

You create an array with the following:

array=(etc)

e.g.

array=(`cat file.txt | uniq -c`)

You can get the size of the array by doing:

size=${#array[*]}