Shell

Shell scripts are a simple way of completing (repetitive) tasks on the command line, much like many programming languages will be used. You will see ~ something — ignore the ‘~’ this is to signify that it is a command entered onto the command line itself.

Writing the code

~ vi helloworld.sh

#!/bin/bash
# My first script
MESSAGE="Hello World!"
echo $MESSAGE

Here we have just entered a really simple example of using variables and returning the value.

Setting the permissions

We need to set permission to allow the script to be executed, this is needed to be done on all unix environments for something to be run

~ chmod +x helloworld.sh

Running the script

~ sh helloworld.sh

Hello World!

Now you should have the response “Hello World!” from running this script.

Going more advanced

Lets explore some of the basic options we have to play with in the shell by example.

Loop test

~ vi looptest.sh

#!/bin/bash
# My first loop
FILETYPES="xml html css js"
for TYPE in $FILETYPES
    do
        echo 'Looking for' $TYPE 'files'
        find . -name '*'$TYPE
    done

Now set the correct permissions and run the script

~ chmod +x looptest.sh
~ sh looptest.sh

Looking for xml files
./somefile.xml
Looking for html files
./somefile.html
Looking for css files
./somefile.css
Looking for js files
./somefile.js

If conditional test

~ vi iftest.sh

#!/bin/bash
# If the file does not exist, make it
FILE='test'
if [ ! -f $FILE ] ; then
    mkdir -p $FILE
fi
ls -las $FILE

Now set the correct permissions and run the script

~ chmod +x iftest.sh
~ sh iftest.sh

Hopefully this is enough to help you on your way to making more use of the powers of Unix…

Further reading

Bash Manual
Useful bash one liner scripts