Lab No 5 Ubuntu Basic Programing Syntax Variables
Variables basically store information. You set variables like this using text editor:
var="FOO"
'var' can be anything you want as long as it doesn't begin with a number. "FOO" can be anything you want.
To access the information from the variable you need to put a '$' in front of it like this:
var="FOO"
echo $var
Try entering those lines into a terminal one at a time; you will see that the first one just gives you another prompt and the second one print FOO.
But that's all a bit boring. So let's make a script to ask the user for some information and then echo that information.
#!/bin/bash
clear
echo "Please enter your name"
read name
echo "Please enter your age"
read age
echo "Please enter yourgender. Male/Female"
read gender
echo "So you're a $age year old $gender called $name"
read allows the user to input information where it is then stored in the variable defined after the read. read variable would take whatever input the user entered and store it in $variable. We then access this with echo and set up a neat sentence. This script is reasonably messy though; read has another function that could halve the size of this script.
clear
read -p "Please enter your name : " name
read -p "Please enter your age : " age
read -p "Please enter your gender. Male/Female : " gender
echo "So you're a $age year old $gender called $name"
That is more efficient code. However it's still a bit messy when run. A solution? Good old white spaces!
clear
read -p "Please enter your name : " name
echo ""
read -p "Please enter your age : " age
echo ""
read -p "Please enter your sex. Male/Female : " gender
echo ""
echo "So you're a $age year old $gender called $name"
Now we have an efficient and clean Bash script.
If Statements
An if statement can be used to check for something and do something else depending on the outcome of the check. For example, if I had an 'apple', I would want to make sure it's still an 'apple' and not an 'orange' because I don't like Oranges!
The syntax for an if statement is
if [something]
then
elif
then
elif
then
....etc....
else
fi
The else if statement or (elif) is not necessary, but it can be used if needed.
An if statement to check if our $fruit variable is an 'apple' would look like this
echo "Please enter type of fruit"
read fruit
if [ $fruit = apple ]
then echo "Good, I like Apples"
else echo "Oh no, I hate Oranges!"
fi
Just to explain this statement,
if [ the contents of $fruit is 'apple' ]
then say "Good, I like Apples"
if it's not, then say "Oh no, I hate Oranges!"
finish
If statements are an easy concept to grasp as they are similar to the "if" used in spoken English. But say you wanted to have 4 or 5 checks, the answer may be to write 4 or 5 statements but that's not the most practical way. This is where elif comes in handy.
if [ $fruit = apple ]
then echo "Good, I like Apples"
elif [ $fruit = pear ]
then echo "Good, I like Pears"
elif [ $fruit = banana ]
then echo "Good, I like Bananas"
else echo "Oh no, I hate Oranges!"
fi
This saves us from from repetitive scripting. There are better ways to check what the fruit is, but we won't go into that now.
Storing application stdout to a variable:
Application stdout ( what you see on the terminal screen, with an un-piped application ) can be saved and used in Bash. The simplest and most elegant way is to use command substitution, by wrapping the code in $(...)
Task 1
fooVar=$(who)
echo $fooVar
This code should output the current users, their respective ttys, and date of login. Note that this strips newlines. Be sure to do any parsing in line ( | grep, etc ) and then pass it to a variable. We will try this again, but grep for tty7, the GUI's tty.
Task 2
fooVar=$(who | grep tty7)
echo $fooVar
This should output the single user that is currently logged into the WM. Let's move on to more advanced data manipulation within command substitution.
Functions
Bash lets you create a function on the fly, really handy if you plan on using a code block more then once. Functions reduce the amounts of editing you have to do in a script, if and when you have to update your script. Let's get to it!
Task 3
Here is an task script:
echo "echo is Called"
echo "Functions are FUN!"
echo "echo is Called"
Although this example is simple, you can see that if you want to change "echo is Called" to say "foo is Called" you would have to edit twice.
Below is the same app using functions.
echoFunction() {
echo "echo is Called"
}
fooBar() {
echo "Functions are FUN!"
}
echoFunction;
fooBar;
echoFunction;
# You call functions without (), just the function name then a semicolon.
This task , as you can see may be longer now, but you can imagine how, adding features, this will eliminate code and reduce complexity. Also, you can see if you want to change the echo call, you have to edit one line, not two.
Debugging
I always find it useful to trace a script to find out why something does not work as expected. To trace, start it through bash explicitly and use the -x option, like so:
bash -x ./script.sh
This will write each command to standard error (preceded by a ‘+ ’) before it is executed.
Other Scripting Languages related to Bash
tr
tr is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts Regular Expressions. Let's do a normally complicated task, transforming a string to all uppercase.
Task 4
read foo
var=$(echo $foo | tr "{a-z}" "{A-Z}")
# {a-z} Matches a through z
# {A-Z} matches A through Z
echo $var
The output should look something like this:
this is a test
THIS IS A TEST
tr also can TRanslate strings, so let's translate all "tar" in $foo to "bar".
Task
echo "Type in: I love tars"
read foo
var=$(echo $foo | tr "t" "b")
echo $var
the output should look something like this:
I love tars
I love bars
Comments:_________________
Date: ______________________. Signature of Lab Instructor:_________
Comments
Post a Comment