Professional Documents
Culture Documents
Summary
You are going to explore more advanced commands in Linux and learn how to write a bash
script.
Activities
Open a web browser and go to http://webminal.org and sign into your account. If you still
don’t have one, you’ll need to create an account with the website (click where it says
‘Register’), then when you are logged in you can access the remote machine.
Click on the ‘Terminal’ link in the menu on the webminal page. You can now log in to the
remote machine using your username and password. When you have done so, you should
see a welcome message appear, and then the command prompt.
find command searches for files in a given directory. Let’s try it:
$cd /etc
$find *.conf
The output should all files that has .conf extension. If you want to find more about it, try the
manual
$man find
Let’s check how many times ‘name’ occurs in manfind.txt (-w for word, -c for count):
$grep -wc name manfind.txt
Regular expressions are very useful when searching (or in any context where you’ve to
handle input/output). A regular expression is a string that describes a search pattern. Let’s
merge it with grep:
$grep -i "^license" COPYING
This is called Anchor matching. It’ll only display lines that start with the word ‘license’
regardless of its case.
Now, let’s try the ‘.’ matcher:
$grep "..cept" COPYING
This will show all lines with words that has two characters and then ‘cept’ 😊
Let’s do more:
$grep "([A-Za-z ]*)" COPYING
This will find each line that contained an opening and closing parenthesis, with only letters
and single spaces in between!
If you want to find out the record of all executed commands so far, use this:
$history
It shows you all the commands you’ve executed. You can use the arrow keys to call
commands from history and save time if you just need to change a small parameter.
alias will help you building your own short commands instead of writing long ones. For
example:
$alias l=’ls -l’
$l
You assigned l to the command ‘ls -l’ so you only have to write l every time you want
to list files/folders in detail. It becomes handy with grep and regular expression commands.
To remove the alias, do this:
$unalias l
To compare two files, you can use the cmp command. By default, cmp returns 0 if the files
are the same; if they differ, the byte and line number at which the first difference occurred
is reported. Assuming you still have the manfind.txt in your home directory:
$cd
$touch myfile.txt
$nano myfile.txt (write something here, save and close)
$cmp manfind.txt myfile.txt
The output should tell you the first line and the first line differ between these two files.
echo is mainly used in interactive scripts. Let’s create our first bash script.
Create a file named myfirstscript.sh
$touch myfirstscript.sh
Open myfirstscript.sh using nano and write the following:
#!/bin/bash
echo "Please enter your name:"
read name
echo "Welcome to Linux $name"
Save and exit. We need now to make this file executable by changing its permissions.
$chmod 777 myfirstscript.sh
Now, execute it as follows:
$bash myfirstscript.sh
Note
When it comes to Linux bash scripts below, spaces are not optional. If you see a space in a
script, then it’s a space. If there’s no space, then there’s no space! Make sure to copy the
scripts in the lab sheet correctly.
Shell scripts are a great way to put many commands together to do a specific job. Let’s try
this. Open your myfirstscript.sh and change to:
#!/bin/bash
# A comment. Other than #!, anything starting with # is ignored
# List current director and REDIRECT the output to a file called
# listing.txt
ls -l > listing.txt
A loop is a block of code that iterates a list of commands as long as the loop control
condition is true. In bash scripting, loops have the following syntax:
Now, let’s try with a sequence. Open the file again and modify the loop as follows:
#!/bin/bash
for num in {1..3}
do
echo “we are on number: $num”
done
Save, close and execute
A bash script can have parameters. Let’s have a look. Create a new bash script file called
parameters.sh and write this into it:
#!/bin/bash
echo The first argument is $1
echo The second argument is $2
How about making sure a specific number of parameters is passed to the script? We need to
learn about if statement first. It has the following syntax:
if [condition]
then
fi
open parameters.sh and replace everything with this code:
if [ "$#" == "0" ]
then
echo You have to give at least one parameter.
exit 1
fi
while (( $# ))
do
echo You gave me $1
shift
done
Then
$bash parameters.sh one two three 1508 “CO1508”
Then
$bash parameters.sh
Ah by the way, you just learnt a special case of while loop! I’m pretty sure you know what
shift does in this context ☺ Let’s have more on while loop.
done
Let’s write a bash script that calculate factorial using while loop. Create a new bash script
file called factorial.sh and write this into it:
#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial
Save it, close and execute like this: (again, don’t forget to give it executable permission)
$bash factorial.sh 5
Did you notice -gt ? it means greater than. If you try to use the symbol > it won’t work
because > is used for directing output. If you want to use > you’ve to put within double
parenthesis. Open the file again and replace the while condition with this:
while (( $counter > 0 ))
-ne
is not equal to
if [ "$a" -ne "$b" ]
-gt
is greater than
if [ "$a" -gt "$b" ]
-ge
is greater than or equal to
if [ "$a" -ge "$b" ]
-lt
is less than
if [ "$a" -lt "$b" ]
-le
is less than or equal to
if [ "$a" -le "$b" ]
<
is less than (within double parentheses)
(("$a" < "$b"))
<=
is less than or equal to (within double parentheses)
(("$a" <= "$b"))
>
is greater than (within double parentheses)
(("$a" > "$b"))
>=
is greater than or equal to (within double parentheses)
(("$a" >= "$b"))
Let’s write a script that will take two numbers, add them together and show the result as
long as the user doesn’t give -1 to exit. Create a new bash script file called whilebreak.sh
and write this into it:
#!/bin/bash
while :
do
read -p "Enter two numbers ( - 1 to quit ) : " a b
if [ $a -eq -1 ]
then
break
fi
answer=$(( a + b ))
echo $answer
done
Save it, close and execute like this: (again, don’t forget to give it executable permission)
$bash whilebreak.sh 4 9
Then
$bash whilebreak.sh -4 -9
Then
$bash whilebreak.sh -1
If we want to nest if else statements, we can use elif as follows. Create a new bash script file
called elif.sh and write this into it:
#!/bin/bash
read -p "Enter a number " num
if [ $num -eq 50 ]
then
echo "You did it! 50 is correct."
elif [ $num -gt 50 ]
then
echo "Too much."
else
echo "Not enough."
fi
Now, modify the code above to make it a guessing game where the user has to guess a
number between 1 and 100. Your script should guide the user until he/she gets right. Your
script will stop only when the users guesses the right number. [Hint: use while loop]
Once you’re done, show it to your tutor.
h script solution