Introduction to Bash Scripting

Here’s a great tutorial for bash scripting: http://www.linuxconfig.org/Bash_scripting_Tutorial

Linux and OS X: Harness the Power of Bash
Linux and OS X: Harness the Power of Bash

If you’re doing any work with Linux or OS X computers, knowing even a little bit of bash can save you a whole lot of work. You can write automated backup scripts, you can scan for faulty permissions… the list is endless. You’ll end up building a toolbox of common scripts that you will use in multiple places.

Only one thing wasn’t given much attention on that page, so I thought I’d point it out:

for next Loop

Usually, your programming syntax is cleaner if you avoid the for next construct and stick to the for each construct instead, however, with bash scripting you often need to work with that crazy little numerical iterator for changing things like file names (e.g. backup1, backup2, …). So you should get familiar with the seq command. It creates an array, going either forwards or backwards, and then bash’s for next loop iterates over that array.

Here’s the seq syntax:

seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST

And here’s how you might iterate backwards over an array:

LIST=`seq $NUMBER_OF_ROLLBACK_FILES_TO_PRESERVE -1 1`;
for I in $LIST; do
echo "I is $I";
done

Now get over to http://www.linuxconfig.org/Bash_scripting_Tutorial and start learning.

3 thoughts on “Introduction to Bash Scripting

  1. One other thing that the tutorial didn’t mention was error checking in bash scripts. In bash, the $? variable contains the last returned value from a command; it goes to a non-zero number if it errors.

    command
    if [ $? -ne 0]; then echo “command failed”; exit 1; fi

    could be replaced with

    command || { echo “command failed”; exit 1; }

    Have a look at this link for more info:
    http://www.davidpashley.com/articles/writing-robust-shell-scripts.html

  2. I found another pitfall… on CentOS at least, you can’t declare an array using the context listed in that article!! In bash, there really AREN’T arrays… you simply treat a string as an array. E.g.

    MY_ARRAY=’1 2 3 4 5′;

    This can be tricky if there are file names with spaces involved…

Comments are closed.