Lab Guide #10

Department of Computer Technology and Information Systems
CTIS156 – Information Technologies II
Fall 2008 -2009
Lab Guide #10
OBJECTIVE: Bash Programmaing
Instructor
Assistant
: Prof. Mustafa AKGUL
: Baran TOPAL
Date :
Week :
18.12.2008
12
Here's the most common shell types:








bash = Bourne again shell
sh = shell
csh = C shell
tcsh = Tenex C shell
tclsh = Tcl shell
ksh = korn shell
ash = a shell
zsh = the Z shell
A shell script is little more than a list of commands that are run in sequence. Conventionally, a shell
script should start with a line such as the following:
#!/bin/bash
This indicates that the script should be run in the bash shell regardless of which interactive shell the
user has chosen. This is very important, since the syntax of different shells can vary greatly.
Variable Declaration:
Linux users can use the declare and typeset commands to declare variables, initialize them, and set
their attributes.
Syntax:
declare [± options] [name [=value] ]
typeset [± options] [name [=value] ]
Commonly used options / features:
-a each 'name' is an array
-f each 'name' is a function
-i 'name' is an integer
-r mark each 'name' read-only ( can not be turned off by using +x)
-x mark each 'name' exported.
Note that using + instead of – turns attributes off.
1.
Check for the bash whether it resides in your machine. (echo $SHELL to display the current shell,
whereis bash or find $BASH or find ./ -name bash)
2.
In your home directory, create a file named as yourname1.sh with touch command and in the
file declare an yourid and yourname and print the output to the console and run it. Do not forget to
change access permission as execution permitted.
(touch baran1.h, write the content:
#!/bin/bash
declare –i id=1234
declare –rx NAME=BARAN
echo $id
echo $NAME
chmod u+x baran1.h and run by the command: ./baran1.sh If fails give the necessary rights to the file to
run by chmod u+x baran1.h,
Output: 1234 BARAN
)
3.
Modify yourname1.sh in your home directory and run it.
#!/bin/bash
declare –i id=1234
declare –rx NAME=BARAN
echo ${name:=$NAME}
echo ${name:+Ulvi} ${id:-$id}
echo $name $id
(vi baran1.sh, ./baran1.sh,
Output:
BARAN
ULVI 1
BARAN 1
)
4.
Modify yourname1.sh in your home directory and run it.
<script>
#!/bin/sh
echo What is your name?
read MY_NAME
echo "Hello $MY_NAME - hope you will pass IT 156 course."
</script>
(vi baran1.sh, ./baran1.sh,
Output:
What is your name?
Baran
Hello Baran – hope you will pass IT 156 course.
)
5.
Modify yourname1.sh with the following code segment and run it.
<script>
#!/bin/bash
echo Please, enter your firstname and lastname
read FN LN
echo "Hi! $LN, $FN !"
</script>
(vi baran1.sh, ./baran1.sh,
Output:
Please, enter your firstname and lastname
baran topal
Hi! topal, baran !
)
6.
Create a directory as yournameyoursurname and create a file named as helloworld.sh with cat
command or vi editor and write a bash program that outputs “Hello World”.
(Traditional 2 hello world script:
<script>
#!/bin/bash
echo Hello World
</script>
<script>
#!/bin/sh
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
</script>
mkdir barantopal, cd barantopal, cat > helloworld.sh, chmod u+x helloworld.sh, ./helloworld.sh, in the
first script, the script has only two lines. The first indicates the system which program to use to run the
file. The second line is the only action performed by this script, which prints 'Hello World' on the
terminal.
If you get something like ./hello.sh: Command not found. Probably the first line '#!/bin/bash' is wrong,
issue whereis bash or how to find where bash is located. 'locate bash' is preferred, but not all machines
have locate. 'find ./ -name bash' from the root dir will work, usually.
Suggested locations to check:
ls -l /bin/bash
ls -l /sbin/bash
ls -l /usr/local/bin/bash
ls -l /usr/bin/bash
ls -l /usr/sbin/bash
ls -l /usr/local/sbin/bash
In the second script, there is an assignment of the string "Hello World" to the variable MY_MESSAGE
then echoes out the value of the variable. Note that, we need the quotes around the string Hello World.
Whereas we could get away with echo Hello World because echo will take any number of parameters, a
variable can only hold one value, so a string with spaces must be quoted to that the shell knows to treat
it all as one. Otherwise, the shell will try to execute the command World after assigning
MY_MESSAGE=Hello)
In bash programming, just like any other programming language, there are test operators.
Test Operators in bash programming:
operator produces true if...
number of operands
-n
operand non zero length
1
-z
operand has zero length
1
-d
there exists a directory whose name is operand
1
-f
there exists a file whose name is operand
1
-eq
the operands are integers and they are equal
2
-neq
the opposite of -eq
2
=
the operands are equal (as strings)
2
!=
opposite of =
2
-lt
operand1 is strictly less than operand2 (both operands
2
should be integers)
-gt
operand1 is strictly greater than operand2 (both operands
2
should be integers)
-ge
operand1 is greater than or equal to operand2 (both
2
operands should be integers)
-le
operand1 is less than or equal to operand2 (both operands
2
should be integers)
Variables:
You can use variables as in any programming languages. There are no data types. A variable in bash
can contain a number, a character, a string of characters.
You have no need to declare a variable, just assigning a value to its reference will create it.
7.
Create a file named as helloIT.sh with cat in your yournameyoursurname directory and run it.
<script>
#!/bin/bash
STR="Hello IT!"
echo $STR
</script>
(cat > helloIT.sh, chmod u+x helloIT.sh, ./helloIT.sh, line 2 creates a variable called STR and assigns
the string "Hello World!" to it. Then the VALUE of this variable is retrieved by putting the '$' in at the
beginning. Please notice (try it!) that if you don't use the '$' sign, the output of the program will be
different, and probably not what you want it to be)
Local variables:
Local variables can be created by using the keyword local.
8.
Modify helloIT.sh as following and run it.
<script>
#!/bin/bash
HELLO=Hello
function hello {
local HELLO=IT
echo $HELLO
}
echo $HELLO
hello
echo $HELLO
</script>
(vi helloIT.sh, ./helloIT.sh, local variable is treated in its own defined scope,
Output:
Hello
IT
Hello
)
Conditionals:
Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an
expression.
Conditionals have many forms. The most basic form is: if expression then statement where 'statement'
is only executed if 'expression' evaluates to true. '2<1' is an expresion that evaluates to false, while '2>1'
evaluates to true.
Conditionals have other forms such as: if expression then statement1 else statement2. Here
'statement1' is executed if 'expression' is true,otherwise 'statement2' is executed.
Yet another form of conditionals is: if expression1 then statement1 else if expression2 then statement2
else statement3. In this form, there's added only the "ELSE IF 'expression2' THEN 'statement2' which
makes ‘statement2’ being executed if ‘expression2’ evaluates to true. The rest is as you may imagine
About syntax:
The base for the 'if' constructions in bash is as follows:
<script>
if [expression];
then
code if 'expression' is true.
fi
</script>
9.
Create a file named as conditional.sh in your yournameyoursurname directory and run the
following.
<script>
#!/bin/bash
if [ "foo" = "foo" ]; then
echo “Expression evaluated as true”
fi
</script>
(cd barantopal, vi conditional.sh, chmod u+x conditional.sh, ./conditional.sh, the code to be executed if
the expression within braces is true can be found after the 'then' word and before 'fi' which indicates the
end of the conditionally executed code, be careful about blanks.
Output:
Expression evaluated as true
)
10.
Modify the conditional.sh file with the following code segment and run it.
<script>
#!/bin/bash
if [ "foo" = "foo" ]; then
echo “Expression evaluated as true”
else
echo “Expression evaluated as false”
fi
</script>
(vi conditional.sh,./conditional.sh, be careful about blanks.
Output:
Expression evaluated as true
)
11.
Modify the conditional.sh file with the following code segment and run it.
<script>
#!/bin/bash
T1="foo"
T2="bar"
if [ "$T1" = "$T2" ]; then
echo “Expression evaluated as true”
else
echo “Expression evaluated as false”
fi
</script>
(vi conditional.sh, ./conditional.sh, be careful about blanks.
Output:
Expression evaluated as false
)
Loops for, while and until:
The for loop is a little bit different from other programming languages. Basically, it let's you iterate over
a series of 'words' within a string.
The while executes a piece of code if the control expression is true, and only stops when it is false (or a
explicit break is found within the executed code.
The until loop is almost equal to the while loop, except that the code is executed while the control
expression evaluates to false.
If you suspect that while and until are very similar you are right.
12.
Create a file named as loop.sh in your yournameyoursurname directory and run the following.
<script>
#!/bin/bash
for i in $( ls ); do
echo item: $i
done
</script>
(vi loop.sh, chmod u+x loop.sh, ./loop.sh, on the second line, we declare i to be the variable that will
take the different values contained in $( ls ). The third line could be longer if needed, or there could be
more lines before the done (4). 'done' (4) indicates that the code that used the value of $i has finished
and $i can take a new value, Output should vary related with ls command result)
(This raises a natural question: why doesn't bash allow the C like for loops for (X=1,X<10; X++) As it
happens, this is discouraged for a reason: bash is an interpreted language, and a rather slow one for
that matter. For this reason, heavy iteration is discouraged)
13.
Modify the loop.sh file with the following code segment and run it.
<script>
#!/bin/bash
for i in `seq 1 10`;
do
echo $i
done
</script>
(vi loop.sh, chmod u+x loop.sh, ./loop.sh
Output:
123456789
with new lines for each element, for single quotation use Alt Gr+comma key on your keyboard)
14.
Modify the loop.sh file with the following code segment using variable and run it.
<script>
#!/bin/bash
myvar=0
while [ $myvar -ne 10 ]
do
echo $myvar
myvar=$(( $myvar + 1 ))
done
</script>
(vi loop.sh, ./loop.sh, the output will be a variable looping exactly 10 times, starting from 0 to 9 with new
lines, be careful about blanks)
15.
Modify the loop.sh file with the following code segment using until and run it.
<script>
#!/bin/bash
myvar=0
until [ $myvar -eq 10 ]
do
echo $myvar
myvar=$(( $myvar + 1 ))
done
</script>
(vi loop.sh, ./loop.sh, the output will be a variable looping exactly 10 times, starting from 0 to 9 with new
lines, be careful about blanks)
16.
Modify the loop.sh file with the following code segment and run it.
<script>
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ];
do
echo “The counter” is $COUNTER
let COUNTER=COUNTER+1
done
</script>
(vi loop.sh, ./loop.sh, the output will be a variable looping exactly 10 times, starting from 0 to 9 with new
lines, be careful about blanks)
17.
Modify the loop.sh file with the following code segment and run it.
<script>
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ];
do
echo COUNTER $COUNTER
let COUNTER-=1
done
</script>
(vi loop.sh, ./loop.sh, the output will be a variable looping exactly 10 times,
Output:
COUNTER 20
COUNTER 19
…
COUNTER 10
)
18.
Modify the loop.sh file with the following code segment and run it.
<script>
#!/bin/bash
X=0
while [ $X -le 20 ]
do
echo $X
X=$((X+1))
done
</script>
(vi loop.sh, ./loop.sh, the output will be a variable looping exactly 21 times, starting from 0 to 20 with
new lines, be careful about blanks)
19.
Modify the loop.sh file with the following code segment and run it.
<script>
#!/usr/bin/env bash
for x in one two three four
do
echo number $x
done
</script>
(vi loop.sh, ./loop.sh
Output:
number one
number two
number three
number four
What exactly happened? The "for x" part of our "for" loop defined a new environment variable (also
called a loop control variable) called "$x", which was successively set to the values "one", "two", "three",
and "four". After each assignment, the body of the loop (the code between the "do" ... "done") was
executed once. In the body, we referred to the loop control variable "$x" using standard variable
expansion syntax, like any other environment variable. Also notice that "for" loops always accept some
kind of word list after the "in" statement)
20. Write the following script to a file named as myfile.sh in your yournameyoursurname directory
and run it.
<script>
#!/usr/bin/env bash
for myfile in /etc/r*
do
if [ -d "$myfile" ]
then
echo "$myfile (dir)"
else
echo "$myfile"
fi
done
</script>
(vi myfile.sh, chmod u+x myfile.sh, ./myfile.sh
Output:
/etc/rc.d (dir)
/etc/resolv.conf
/etc/resolv.conf~
/etc/rpc
The above code looped over each file in /etc that began with an "r". To do this, bash first took our
wildcard /etc/r* and expanded it, replacing it with the string /etc/rc.d /etc/resolv.conf /etc/resolv.conf~
/etc/rpc before executing the loop. Once inside the loop, the "-d" conditional operator was used to
perform two different actions, depending on whether myfile was a directory or not. If it was, a " (dir)" was
appended to the output line)
21. Write the following script to a file named as traffic.sh in your yournameyoursurname directory
and run it.
<script>
#!/bin/bash
colour1="red"
colour2="yellow"
colour3="green"
for X in "$colour1 $colour2 $colour3"
do
echo $X
done
</script>
(vi traffic.sh, chmod u+x traffic.sh, ./traffic.sh
Output:
red yellow green
)
22. Write the following script to a file named as operation.sh in your yournameyoursurname
directory and run it.
<script>
#!/bin/bash
echo $(( 100 / 3 ))
myvar="56"
echo $(( $myvar + 12 ))
echo $(( $myvar - $myvar ))
myvar=$(( $myvar + 1 ))
echo $myvar
</script>
(vi operation.sh, chmod u+x operation.sh, ./operation.sh, you can perform simple integer math using
shell constructs. Simply enclose the particular arithmetic expression between a "$((" and a "))", and
bash will evaluate the expression.
Output:
33 68 0 57
)
Functions:
As in almost any programming language, you can use functions to group pieces of code in a more
logical way or practice a recursion.
Declaring a function is just a matter of writing function my_func { my_code }.
Calling a function is just like calling another program, you just write its name .
23. Write the following script to a file named as function.sh in your yournameyoursurname
directory and run it.
<script>
#!/bin/bash
function quit {
exit
}
function hello {
echo Hello!
}
hello
quit
echo foo
</script>
(vi function.sh, chmod u+x function.sh, ./function.sh
Output: Hello!
Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function If you are not absolutely sure
about what this script does, please try it!. Notice that a functions don't need to be declared in any
specific order. When running the script you'll notice that first: the function 'hello' is called, second the
'quit' function, and the program never reaches line 10 (echo foo line))
24.
Modify the function.sh file with the following code segment and run it.
<script>
#!/bin/bash
function quit {
exit
}
function e {
echo $1
}
e Hello
e World
quit
echo foo
</script>
(vi function.sh, ./function.sh, this script is almost identically to the previous one. The main difference is
the funcion 'e'. This function, prints the first argument it receives. Arguments, within functions, are
treated in the same manner as arguments given to the script)
Command substitution:
One very handy thing to know is how to create an environment variable that contains the result of an
executable command. This is very easy to do:
25. Write the following script to a file named as substitute.sh in your yournameyoursurname
directory and run it.
<script>
$ MYDIR=`dirname /usr/include/math.h`
$ echo $MYDIR
</script>
(vi substitute.sh or cat > substitute.sh, chmod u+x substitute.sh, ./substitute.sh,
Output:
/usr/include
What we did above is called "command substitution".
On the first line, we simply enclosed the command we wanted to execute in back quotes. Those are not
standard single quotes, but instead come from the keyboard key that normally sits above the Tab key.
We can do exactly the same thing with bash's alternate command substitution syntax:
$ MYDIR=$(dirname /usr/include/math.h)
$ echo $MYDIR
As you can see, bash provides multiple ways to perform exactly the same thing. Using command
substitution, we can place any command or pipeline of commands in between ` ` or $( ) and assign it to
an environment variable)
26.
Modify substitute.sh in your yournameyoursurname directory and run it.
<script>
MYFILES=$(ls /etc | grep pa)
echo $MYFILES
</script>
(vi substitute.sh or cat > substitute.sh, ./substitute.sh,
Output:
baran baran1 baranc barannn… (will vary in your machine)
)