You are on page 1of 11

Page 1 of 11

CO1508 Computer Systems & Security – Week 15 – Linux


Bash Scripting and Advanced Commands

Summary
You are going to explore more advanced commands in Linux and learn how to write a bash
script.

Activities

1. Linux terminal – Advanced Commands

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.

1.1 Advanced Commands – find

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

1.2 Advanced Commands – grep

First, create a text file like this in your home directory:


$cd
$man find > manfind.txt
Now, let’s try and find lines in this text files that contain the word ‘name’:
$grep name manfind.txt

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 2 of 11

Let’s check how many times ‘name’ occurs in manfind.txt (-w for word, -c for count):
$grep -wc name manfind.txt

grep is a very powerful command. Let’s explore it further.


$cd /usr/share/licenses/gmp-6.0.0
$grep -i "license" COPYING
As you can see, the result shows the word ‘license’ in any case (-i means ignore case). Now,
let’s try to find all lines (numbered) that do NOT contain the word ‘license’
$grep -vn "license" COPYING
-v invert match while -n gives a line number.

1.3 Advanced Commands – Regular Expressions

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 move on to bracket expressions:


$grep "t[ow]o" COPYING
This will match any words that contain either ‘too’ or ‘two’
Now, let’s do this:
$grep "^[A-Z]" COPYING
What happened?

Let’s do more:
$grep "([A-Za-z ]*)" COPYING

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 3 of 11

This will find each line that contained an opening and closing parenthesis, with only letters
and single spaces in between!

Let’s try to find all words that have triple-vowels:


$grep -E "[AEIOUaeiou]{3}" COPYING
Okay, enough with this for now! The point is: regular expressions are very powerful
instrument. Make sure you learn it in your own time.

1.4 Advanced Commands – history

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.

1.5 Advanced Commands – cal

This command will show the calendar.


$cal
A good use is to check past and future calendars. For example, check November 1916 to find
out which day was the 18th
$cal 11 1916
Do you know what happened on 18th of November 1916?
P.S. you can look into future calendars too … find our when is your birthday in 2050 ☺

1.6 Advanced Commands – alias

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

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 4 of 11

1.7 Advanced Commands – cmp

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.

1.8 Advanced Commands – echo

As the name suggests, it echoes a text on the standard output.


$echo “This is an echo test”
You can direct the output to a file like this:
$echo “This is an echo test” > myfile.txt

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.

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 5 of 11

2. Linux Bash Scripting

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

Save, close then execute.


$bash myfirstscript.sh

2.1 Linux Bash Scripting – Variables

Create a new script called vars.sh and write the following:


#!/bin/bash
var1=15
var2=90
echo $var1 $var2
Save, close and execute.
Let’s try to put commands in variables. Open the file again and replace the contents with
this:
#!/bin/bash
DATE=$(date)
PWD=$(pwd)
echo “Date and time is: $DATE”
echo “Your current directory is: $PWD”
Save, close and execute.

2.2 Linux Bash Scripting – Loops and Sequences (for)

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:

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 6 of 11

for arg in [list]


do
command(s)
done
Create a new bash script file called loops.sh and write this into it:
#!/bin/bash
for num in 1 2 3
do
echo “we are on number: $num”
done
Save, close and execute. [Don’t forget to give loops.sh an executable permission!]

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

Another way to do it is this:


#!/bin/bash
for num in $(seq 1 3)
do
echo “we are on number: $num”
done
Save, close and execute

2.3 Linux Bash Scripting – Script Parameters

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

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 7 of 11

echo The third argument is $3

echo Total number of arguments $#


echo All arguments $* all the arguments
Save, close and execute like this:
$bash parameters.sh one two three
Modify the script to include this line of code:
echo my name is $0
Save, close and execute like this:
$bash parameters.sh one two three
$0 displays the name of the script itself.

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

Save, close and execute like this:


$bash parameters.sh one two three

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 8 of 11

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.

2.4 Linux Bash Scripting – While loop

The while loop in bash scripting has the following syntax:


while [ condition ]
do

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 ))

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 9 of 11

The following explain integer comparison operators in bash scripting:


-eq
is equal to
if [ "$a" -eq "$b" ]

-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"))

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 10 of 11

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

2.5 Linux Bash Scripting – if then elif

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

CO1508 Computer Systems and Security, UCLAN – 2019-2020


Page 11 of 11

Save, close and execute like this:


$bash elif.sh 40
Then
$bash elif.sh 70
Then
$bash elif.sh 50

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

CO1508 Computer Systems and Security, UCLAN – 2019-2020

You might also like