Introduction to Bash Scripting

Here’s a great tutorial for bash scripting:

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:


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

for I in $LIST; do
echo "I is $I";

Now get over to 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.

    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:

  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.