Shell Scripting - Basics

A shell script is just a text file with a collection of commands. You can tell the compture to ‘run’ the script, and all the commands in it will be run sequencially.

Basic example of creating a script

  1. Create a text file called myScript

  2. Run chmod u+x myScript

  3. Add #!/bin/bash on the first line of myScript

  4. Add commands after that, each on seperate lines, to myScript

  5. ./myScript will run your script

You can put any syntax that you normally used on the command line, in a script, like arguments, IO redirection, pipes, etc. You can also set variables, create if statements, for loops, and much more. In fact, you can even do those things on the command line, but a script makes it more convienent for using those things.

Variables

To set a variable:

myVar=4

Note that you cannot have spaces before/after the equal sign, otherwise bash (the shell/interpreter/language) will think that myVar is a command and ‘= 4’ are its arguments.

To access the value of a variable, prepend it with a ‘$’:

echo $myVar

If Statements

if [ $myVar == 4 ] 
then
    echo yes
fi

Note that whitespace/newlines matter in bash. The ‘then’ keyword can't be put on the same line as the ‘if’ like this:

if [ $myVar == 4 ]  then
    echo yes
fi

But you can use a semicolon ‘;’ in place of a newline. The following will work:

if [ $myVar == 4 ] ; then
    echo yes
fi

Better If Statements

There's a more compact way of making if/then logic:

[ $myVar == 4 ] && echo yes

That will run echo yes if myVar == 4

Now, this will run echo yes if myVar is not equal to 4

[ $myVar == 4 ] || echo yes

Essentially, the && runs the command that follows it, if the previous expression evaluates to true, or if preceded by a command, if the command didn't have an error. Similarly, || will run the next command if the previous expression/command was false or had an error.

You can chain && and ||.

For example, the following command only runs cmd > myFile if the file ‘myFile’ doesn't exist. This is useful to avoid overwriting myFile.

[ -f myFile ] || cmd > myFile && echo "File exists"