Quantcast
Linux Hacks

Linux Hack of The Week #4: Shell Scripting

By June 22, 2018 No Comments

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.

#!/bin/bash

Loops

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

#!/bin/bash

teams=”Broncos Avalanche Rockies”

for each in $teams

do

echo $each

done

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

Broncos

Avalanche

Rockies

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

do

echo $line

done

If/Then/Else

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

startTrekTheNextGen=2

starTrekTheOrginal=1

if [ $starTrekTheNextGen -gt starTrekTheOriginal ]

then

echo “Piccard Forever”

else

echo “KAAAAAAHHHHHHN”

fi

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

Switches

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.

#!/bin/bash

if [ -z $1 ]

then

       echo “ERROR: Please provide an argument”

       exit

fi

case $1 in

       “tos”)

               echo “The Original Series”

               ;;

       “tng”)

               echo “The Next Generation”

               ;;

       “ds9”)

               echo “Deep Space Nine”

               ;;

       *)

               echo “I haven’t watched that yet”

               ;;

esac

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

Author Joe McManus

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

Leave a Reply