Bash (Shell) Scripting for Beginners

Jan 8, 2012 04:14 PM

Bash (Shell) Scripting for Beginners

Intro

I am an occasional Linux user currently playing around in CrunchBang and loving it.

Prior to this, I used to dual-boot Windows and xfce-buntu (or xubuntu) at work, and due to some unforeseen circumstances, my screen always went fuzzy on logon.



This has something to do with crappy hardware on the stock work PC, which wasn't playing well with xfce. My attempts to fix this via drivers and configs failed miserably. So I had to go to xrandr (which is the app I used responsible for screen settings), and change the resolution to a lower one, reverting to the desired res to get rid of the fuzzy output.



This got boring very quickly so I started looking into a way to automate it and run on start-up.

This is how I got into bash (or Shell) scripting, and I am still learning its intricacies.



In this guide, I will attempt to show you how to start scripting with bash and how to build your first bash applet.



The Basics

Find a empty directory to work with, or just go to /home/yourusername/ and make a folder called 'scripts' or something like that. 

Then inside that folder, create a new file and call it "firstbash.sh"

Once that is done, fire up your terminal and enter: ''name of your text editor'' /home/yourusername/scripts/firstbash.sh

For me it would be: geany /home/user/scripts/firstbash.sh

Leave a space between the name of your text editor and the path to your script. This will open the script for editing in your default text editor. 

Once this is complete, let me introduce you to the very first line in your script. 

#! /bin/bash

This line will tell your terminal where the bash script engine is located. What I wrote seems to be the default location in most distro's, so just copy and slap it into your file.

Next, comes the ''echo''; Echo is a command which tells the script to display a string (text). For example, a script that says:

#! /bin/bash 

echo "HELLO" 

echo "HOW ARE YOU?"

Will show up as below in your terminal: 

Hello 

How are you?

You will be using echo for those times that your script requires to display something to the user. To insert a blank line, just use:

echo



(without the quotation).



But what good is a script that does not require input? Let us get acquainted with ''read'' and variables.



Read basically tells the script to read the user's input. In this particular instance, we will tell the script to read what the user typed in and then display it back by storing it in a variable which we will name MYVAR, sounds good?



So, your script would be:



#! /bin/bash

echo "+------------+"

echo "| HELLO USER |"

echo "+------------+"

echo 

echo "How have you been?"

read MYVAR

echo "Did you say "$MYVAR" ?"

echo "I have also been "$MYVAR""

echo "..."

echo "....."

echo "I saw a deer today..."



So, to re-cap, our script has asked the user for input, then stored it inside a variable and read out the variable back to the user inside some text.



To test it out, just fire up the terminal and enter:

bash ~scripts/firstbash.sh



This will execute the script in your terminal.

Advanced Example: Conditions

So, that was not so scary, was it? Time for some conditional input.

If you are at all familiar with programing, you will be aware of the fact that there is not a program which does not utilise some form of a conditional statement in its source.

Be it if, where, while, for or what have you, these are used in everyday programming.

We will use IF for this example.

#! /bin/bash

echo "+------------+"

echo "| HELLO USER |"

echo "+------------+"

echo

echo "Please press 1"

read myvar

if "$myvar" -eq 1

then 

echo "Well done!"

else

echo "I told you to press 1 didn't I?"

fi

Pay close attention to the ''IF" statement.

Let's dissect it.

if ["$myvar" -eq 1 ] - this means, IF the variable (myvar) into which you provided your answer is equal (-eq) to one, then print out "Well done!"

else print out "I told you to press 1 didn't I?"

fi - this just closes the IF statement.

So the logic is pretty simple, isn't it?

if, then, else, fi condition,result if condition is met, result if condition unsatisfied,end.

Anyone working with Calc or Excel will no doubt remember their if's as being pretty much the same. =IF(SUM(A1:A3)>0,"YES","NO")

Be aware that nested IF statements have to be structured properly to work. Correct example of a double IF:

if"$myvar" -eq 1

then 

   echo "Well done!"

else

if"$myvar" -eq 2

             then 

                                    echo "Well done!"

                        else

                        echo "LOL u noob!"

fi 

fi

All it says is, if you didn't press 1, but pressed 2, then that is fine. If, however, you failed to press 1 or 2 in both attempts, you get the ''LOL'' message. The two FI's at the end close both IF's properly, as the second if is part of the first IF's else condition.

Try it out on the terminal!

Time for another neat trick - sleep. (No, really, as in the script kind of sleep.)

sleep - tells the script to pause between outputs.

The usage would be:

echo "Hi"

sleep 2

echo "What's up?"

Here we told the script to say "HI" and sleep for two seconds, then say "What's up?". Let's use our very first script, and modify it with ''sleep'' in appropriate places.

#! /bin/bash

echo "+------------+"

echo "| HELLO USER |"

echo "+------------+"

echo 

sleep 2

echo "How have you been?"

sleep 2

read MYVAR

sleep 2

echo "Did you say "$MYVAR" ?"

sleep 2

echo "I have also been "$MYVAR""

sleep 2

echo "..."

sleep 3

echo "....."

sleep 4

echo "I saw a deer today..."

You will notice how there are significant time gaps between script outputs. This is useful if you want to let the user's eyes catch up with a lot of text output they need to pay attention to.

 A Quick Intro to Functions

Functions just store your script commands for later use and can be executed on prompt, as many times as you require. Useful and saves space instead of having to re-type them whenever you need to use it again.

So a quick example:

function sample {

echo "sample"

echo "sample0"

echo "sample1"

}

Now here's what the script would look like:

#! /bin/bash

function sample {

echo "sample"

echo "sample0"

echo "sample1"

}

sample

sleep 3

sample

sleep 2

Conditional Script to Change Resolution in Xrandr

Time for the last example in bash scripting. You will now combine all of the above examples to create a simple script, which will change your resolution upon prompt. It can also be set to run at startup, by modifying it slightly.

First of all, we will declare two main functions in the script. One which closes the script, when you are done with your changes, and another which actually changes the resolution. 

So let us begin.

#! /bin/bash

function quit {

                  exit

             } 

function mainmenu {     

echo "Hello user!"

echo 

echo 

echo "Please press 1 to change resolution."

echo "Press 9 to quit this program."

read  selection

if "$selection" -eq 1

then 

   echo "You have opted to Change Resolution"

   echo

   echo "Please enter the desired resolution in the following format: [width]x[height], for example - 1920x1080. Below is a list of available resolutions:"

   echo "----------------------------------------------------------------------"

   xrandr

   echo "----------------------------------------------------------------------"

   echo "Please enter your resolution now:"

   read resolution

   sleep 1

   xrandr -s "$resolution"

   sleep 1

   echo "Resolution changed to $resolution"

   echo

   echo

   mainmenu

   return

else

if "$selection" -eq "9"

then

   echo "Closing..."

   sleep 1

   quit

else

echo "invalid choice"

mainmenu

fi 

fi

}

mainmenu

To enable this to run at start-up, copy your new script. Let's call it "resch.sh" into

/etc/init.d/

Create a shortcut to your script and dump that shortcut into

 /etc/rc.d/rc5.d/

Then rename that shortcut so it looks like this: s20resch.sh 

The ''s20'' prefix will define the order of the script to be run. So your resolution change script will be executed before the S21 scripts, but after S19 scripts.

It is not vital to have the number higher or lower, just have it there.

And, I do believe that is it for now. The very basic rundown of how bash scripting works with a few working examples. Remember that bash scripts are very powerful and can be utilised for many things. You can even build an installer with it! Why don't you play around with them and see what you can uncover? I hope this clarified the functions that were used in bash and will encourage you to seek out and build your own scripts and share them with other users.

Image by Evil Mad Scientists

Comments

No Comments Exist

Be the first, drop a comment!