Linux Hacks

Linux Hack of The Week #4: Shell Scripting

One of the reasons we (I use we, I mean afterall you are reading a post on shell scripting) love Linux is because of the ease of automation. A big part of that is using BASH (Bourne Again Shell) to script some common tasks.

Start off your script defining the interpreter, what everyone calls the shebang line.



As an example we’ll make a variable and do a for each loop through them.


teams=”Broncos Avalanche Rockies”

for each in $teams


echo $each


Now how do you run that? You could run bash ./myScript.sh , but that is 5 extra characters you don’t need to type. You will chmod it.

chmod 755 myscript.sh

Then you would run it with ./myScript.sh

joes-MacBook-Pro:~ joe$ ./myscript.sh




There are also while loops, which work well if you are looping through a list of files that may have spaces in the name.

ls | while read line


echo $line



Bash has if statements, it’s just a little unique. It’s unique in that spacing is very important and [ ] if else are all commands that are invoked. Let’s look at an example



if [ $starTrekTheNextGen -gt starTrekTheOriginal ]


echo “Piccard Forever”




You see a -gt for greater than. There are a number of test conditions for bash, but here are the ones I use most:

-eq: equals

-gt: greater than

-lt less than

-eq: equals

-ge/le/: greater/lesser than or equals

-z: null

-n: not null


Even though I love Python, it’s lack of a switch statement bothers me. But fear not, Bash has switch statements. The are opened with case and closed with esac. A wildcard can be used to with an asterisk.


if [ -z $1 ]


       echo “ERROR: Please provide an argument”



case $1 in


               echo “The Original Series”



               echo “The Next Generation”



               echo “Deep Space Nine”



               echo “I haven’t watched that yet”



That is just a primer on shell scripting. If you want to learn more, track down the book Linux and Unix Shell Programming by David Tansley. Thanks for reading and come back every Friday for a new Linux hack!

Joe McManus, CISO

Author Joe McManus, CISO

Joe is a Senior Cyber Security Researcher at CERT and a Professor at the University of Colorado College of Engineering where he teaches graduate courses in information security and forensics. Recently, Joe was the Director of Security at SolidFire, (acquired by NetApp [NTAP]). He is an avid cyclist, climber and leads the Automox security team.

More posts by Joe McManus, CISO

Leave a Reply