jbsnake's
Intermediate Tutorial
written by jbsnake, reposted by crouse.
----------------------------------------------
If you havn't read the
beginner tutorial, I suggest you stop now and read it first. If you have read it, congratulations! You can officially write what I call a "dumb" script. I say it's a dumb scrip because it contains no logic. It simply goes from the top of the script to the bottom executing code as it goes.
Logic is pretty easy to implement once you know the key words. The most basic logical expression is
if. Logical expressions help direct the flow of logic within a script. A good example of that is at the beginning of this tutorial. <b>If</b> you havn't read the beginner tutorial... In a shell script that would look something like this:
Code:
if [[ ! $readBeginningTutorial ]]
then
exit
fi
An
if statement's syntax is pretty easy, it <u><b>must</b></u> start with the word
if, followed by a condition ($a = $b), on the next line it <u><b>must</b></u> have the word
then. The next few lines are commands to execute if the above mentioned condition is met. The
if statement is then closed using the word
fi (if backwards). The brackets ([[ ]]) surrounding the condition are not always needed, it depends on the condition. I personally always use the brackets just to help me keep things uniform. That way I can easily spot al my conditions in my scripts. I think thats enough babbling about the
if statement. Let's actually write some
if statements so you can see what all the stuff I said above is actually doing.
For out first example, let's do something easy. Don't forget the needed stuff at the beginning of your script!
Code:
#!/bin/bash
if [[ 1 == 2 ]]
then
echo "You will never see this while executing this script!";
fi
The above example checked to see if 1 was equal to 2. Since that condition can never be met, the
echo command will never execute. Here's another example:
Code:
#!/bin/bash
if [[ 1 == 2 ]]
then
echo "This will never execute";
fi
echo "This will execute no matter what the condition is"
echo "because it is outside of the if statement."
I know what you are thinking. "That's great and all, but how can I check to see if it's either true or false?". Answer:
elif.
Elif is bash's version of Else If. A quick example of that:
Code:
#!/bin/bash
if [[ 1 == 2 ]]
then
echo "Not Possible";
elif [[ 1 != 2 ]]
then
echo "Always Prints";
fi
<u><b>Note</b></u>:
Spacing is very very important. [[<sp>
condition1<sp>
expression<sp>
condition2<sp>
]] Notice
elif took a condition. It <u><b>must</b></u> have a conditional expression just like if does. You can also use
else instead of =
elif, or in addition to. Example:
Code:
if [[ 1 == 2 ]]
then
echo "yea, right";
else
echo "always prints";
fi
<u><b>Note</b></u>:
I'm not going to keep writing an entire script for each example, just the part I'm focussing on. In the above example, you'll notice
else doesn't take a condition like
if and
elif. That's because
else executes if none of the other conditions within the if statement are met. Example:
Code:
if [[ 1 == 2 ]]
then
echo "condition can't be met";
elif [[ 1 > 2 ]]
then
echo "condition can't be met";
else
echo "only thing that will print";
fi
Notice only the commands in the else portion execute. An
else and/or an
elif are skipped if the
if condition is met. Example:
Code:
if [[ 1 == 1 ]]
then
echo "This is all that executes"
echo "Well, besides this"
echo "But that is because it's all in the"
echo "Same block of code"
elif [[ 2 == 2 ]]
then
echo "Even though is condition is met"
echo "None of this will print because"
echo "The if condition was already met"
else
echo "This is skipped"
fi
I personally don't care much for
elif. If I have more than true or false for a condition, I'll use a
case statement. A
case statement checks one variable for multiple possible conditions. Example:
Code:
bob="one"
case $bob in
"one") echo "one";
bob="two";
;;
"two") echo "two";
bob="three";
;;
"three")echo "three";
bob="four";
;;
*) echo "anything else";
;;
esac
After reading this tutorial this far, you're probably saying "So?". If you already knew the enclosed information, you have probably written a few programs in the past. I wrote this tutorial for someone with no background experience in programming in mind. For the programmers that read this, I would just pay attention to the syntax.
Now let's put this tutorial to use. I think we should write a little menu driven script. We will use
if-then-else and
case. Along with some bonus material (a loop) thrown in for kicks. Open a terminal window and type:
Code:
cd
echo "#!/bin/bash" > menuScript
Now that the first (not to mention most important) line of your script is written, open it in your favorite editor (fyi: the script is named "menuScript"). I usually use vi, but kate is my favorite GUI editor. Under the first line let's make some variables.
Code:
#!/bin/bash
### start variables ###
ans=""
choice=""
### end variables ###
After the variables, I suggest writing the functions we'll use.
Code:
### start functions ###
function yesno
{
passedVar=$1
####################################################
# use part of the variable passed. start with the 0 position and the
# length is one (first letter).
####################################################
ans=${passedVar:0:1}
###################################################
# pipe the varible to tr and make all uppercase letters lowercase
###################################################
ans=`echo $ans | tr [:upper:] [:lower:]`
if [[ $ans -eq "y" ]]
then
return 0;
elif [[ $ans -eq "n" ]]
then
return 1;
else
echo "*** Yes or No only!! ***;
fi
}
### end functions ###
Now you can start the main body of the script. Keep in mind you can obviously create more functions, thus writing less in your main body, not to mention cutting down on repeating alot of the same code. This is called modularization (this essence of object oriented coding). If you write your functions well, you can usually just copy and paste the same functions from one script to another (something I love to do). Or you can create a function library, I may get into that in another tutorial).
Back on track, let's write our main body:
Code:
### start main ###
echo "Please choose one of the following:"
echo "1) Echo the current directory"
echo "2) List the contents of current directory"
echo "3) Echo who is logged onto your computer"
echo "4) Echo who is running this script"
echo "0) Exit"
read choice
while [[ $choice != 0 ]]
do
case $choice in
1) clear;
pwd;
;;
2) clear;
ls;
;;
3) clear;
who;
;;
4) clear;
whoami;
;;
0) clear;
echo "Hope you enjoyed writting/running this!";
exit;
;;
*) clear;
echo "Not a valid selection!";
;;
esac
echo "Please choose one of the following:"
echo "1) Echo the current directory"
echo "2) List the contents of current directory"
echo "3) Echo who is logged onto your computer"
echo "4) Echo who is running this script"
echo "0) Exit"
read choice
done
Ofcourse there is so very much more you could do with the example I gave you. That is up to you. Notice I didn't even use the function I wrote, that also is for you. See if you can't come up with a way to incorporate that function into this script, or another script you may write. Hope you have enjoyed reading this. Keep an eye out for the next installment of my bash tutorials (there only going to get harder

)