How To: Bash (Shell) Scripting for Beginners

Bash (Shell) Scripting for Beginners

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.

Step 1 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.

Step 2 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.

Step 3  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

Step 4 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

17 Comments

Wow! This is great! Thank you so much for the contribution.

No probs. I hope it helps someone begin scripting in bash. I know I was intimidated at first, and the way I got into it was because I was curious how someone wrote a Minecraft installed script. So I went through it line by line trying this and that and ended up learning in the process. Hope I can share some other stuff in the near future.

/me wants code tags for Null Byte.

Nice guide and did anyone else notice the portal 2 reference?

Thanks. It seemed appropriate to include this. Have you tried the tutorial out ?

I haven't tried it out yet but I might in the near future

Reminds me of a friends code, haha. Everytime I see his configs and code, he's got the most hilarious variable and function names xD.

Thanks nice guide, how about declaring static variables and samples of while, do while, for loops.

Thanks for this guide...you have gotten me started in scripting. One question:

I keep getting problems with the if statement, the one under "Step 2". The error is usually "command not found". For instance, my if statement is on line 8:

firstbash.sh: line : 1: command not found

So it looks like it's having problems with the number. I'm clueless as to the reason.
Thanks for your help!

Jared;

Did you start your script with #! /bin/bash ?

OTW

Yes indeed
Here is the script, word for word:
------------------------------------------------
#! /bin/bash
echo "Please enter a number: "
read num
if "$num" -eq 1
then
echo
echo "Your number is 1"
else
echo
echo "Your number is greater than 1"
fi
-------------------------------------------------

And the error message:
-------------------------------------------------
$./firstbash.sh
Please enter a number:
1
firstbash.sh: line 4: 1: command not found

your number is large
--------------------------------------------------

Sorry for the trouble and thank you for the help

Jared:

In line 4 you are coming a string value to a numeric value. That's why you are getting the error.

OTW

I have tried:
$num = 1
$num == 1
$num -eq 1
"$num" = "1"
"$num" -eq "1"

They all give the same error:
firstbash.sh: line 4: 1: command not found

"$" brings out the value of a variable right? Like dereferencing a pointer? So $num = 1 should turn into 1 = 1 ...but it doesn't obviously.

Thank you for your help

I have made my own example that seems to work. It makes it so that if the user says, "hey", some text will come up, and anything else they write will come up as "nope".

#!/bin/bash
read myvar
if "$myvar" = "hey" ; then
echo "expression evaluated as true";
else
echo "nope";
fi

I've figured it out.
When doing if else commands, make sure you have the brackets.
like:

if ["test" = "test]; then
echo "test"
else
echo "test"

but absolutely make sure you have a space in between the first bracket, and the variable:

if [ "test" = "test" ] then
echo "test"
else
echo "test"

CORRECT ANSWER:

For those who've actually done this tutorial, I'm sure you've realized the if/then examples don't work. That is because the screwy way this site formats the text. Here is the correct code.

*Basically what was missing is:
if [<space>"variable"<space>];
and quotation marks around the selection

For example: says:
if "$selection" -eq 1 <---
when it's supposed to say: if [ "selection" -eq "1" ] ;

Here is the correct script:
#! /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" == "1" ] ;

then

echo "You have opted to Change Resolution"

echo

echo "Please enter the desired resolution in the following format: widthxheight, 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" == "9" ] ;

then

echo "Closing..."

sleep 1

quit

else

echo "invalid choice"

mainmenu

fi

fi

}

Share Your Thoughts

  • Hot
  • Latest