Introduction to Bash Scripting

December 9, 2008 - Reading time: 2 minutes

Here’s a great tutorial for bash scripting: https://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 https://linuxconfig.org/bash-scripting-tutorial and start learning.

About

Tech tips, reviews, tutorials, occasional rants.

Seldom updated.