Lab 05 - Scripting (W2022)
Lab 05 - Scripting (W2022)
Scripting
Objectives
Consolidate usage of the Shell Commands as a means for system management
Get familiar with the basics of Shell Script tasks in Linux
Activities
Shell commands allow the user to navigate and manipulate the system. When you log in, the
system will place you in your home folder indicated by “~” symbol in the prompt and that is
typically located in /home folder. A non-super user has limited permissions inside its home folder
only. For security reasons, only the super user has access to all files and folders.
Every Linux process has three communication channels available: standard input (STDIN),
standard output (STDOUT) and standard error (STDERR). The Shell refers to these channels as
0, 1 and 2 respectively. The symbol < is used to redirect STDIN while >, >> are used to redirect
STDOUT to a specific file (> for overwriting and >> for appending)
1. Change directories (cd) to you home folder (~) if you are not already there with: cd ~
2. Using vim, create an empty file in your home folder called hello.sh: vim hello.sh
3. Press “i” key to enter INSERT mode
4. Add the following code in the first line: #!/bin/bash
5. Add a comment in the next line with: #This is a basic shell script
6. Add the following code in the next line: echo "Hello World!"
7. You should end up with below contents in your file
hello.sh
#!/bin/bash
#This is a basic shell script
echo "Hello World"
8. Press ESC to exit INSERT mode ( ---INSERT--- should disappear from the bottom of your
screen)
9. Type “:wq” (write and quit) and Enter to save changes and exit VIM. Make sure you are
out of VIM and back into the command prompt.
10. Execute the new script by typing ./hello.sh
11. You should get an error “Permission denied”. This is because the new file does not
have execution permission.
12. List the details of the hello.sh file with ls -l hello.sh
13. You will see the permission section (the first 10 characters from the left) -rw-rw-r--
14. In order to add execute permission to the new file type: chmod +x hello.sh
15. Again, list the details of the hello.sh file with ls -l hello.sh
16. What has changed?
17. Try to execute the script again with ./hello.sh
18. The command prompt should display “Hello World!” as expected
19. Re-open your hello.sh file and add the following line underneath the existing text:
echo "Today is $(date)"
20. Save your file and quit vim with :wq
21. Run the script again (use ./) – the current time and date should also be displayed.
22. If everything works, continue on (you don’t have to show your instructor the output)
Variables
In the last section, you used a variable, $(date). There are other variables such as $HOME and
$USER. These are called global environment variables and they are system-created for each user
on login. To display a list of your current environment variables type the command env in the shell.
User variables cannot have the same name as global variables.
To define a user variable, write the name of the variable followed by the equals sign and then the
value you want to assign to it. Note there are NO SPACES on either side of the equals sign
(variable assignment won't work otherwise)
User now can refer to the defined user variable by prepending a dollar sign (e.g. $TEXT, $NUMBER)
Activity 1. Create a new script called variables.sh then add the code below.
variables.sh
#!/bin/bash
TEXT="This script makes a sum of two numbers using Arithmetic Expansion with
the format: result=\$((n1+n2))"
X=131
Y=289
Z=$((X+Y))
echo $TEXT
echo $X + $Y = $Z
Save your changes, then test the script and view the output.
If it works (and ONLY if it works) continue to the next section (you do not have to show your
instructor this part). If it did NOT work, review the steps in Part B above.
User-defined parameters
The previous script used variables which were already defined in the script (X=131 and Y=289).
The user also has the option of inputting “parameters” when executing a script from the command
line. In the command line, each word written after the script name is considered a parameter. The
shell passes these parameters to the script and uses the variables $1 for the first parameter, $2
for the second parameter and so on. Variable $0 always represents the name of the script.
Activity 2. Create a script that multiply two numbers entered by the user.
If structure syntax:
if [ condition ]
then
line1
line2
...
fi
Expressions line1 and line2 will only execute if condition is true. The condition is a logical
operation enclosed in square brackets, with the following syntax (observe the spaces both inside
AND outside the square brackets!)
Modify the variables.sh script to compare two numbers and display a result accordingly.
variables.sh
#!/bin/bash
#Simple sum
TEXT="This script makes a sum of two numbers using Arithmetic Expansion with
the format: result=\$((n1+n2))"
X=131
Y=289
Z=$((X+Y))
echo $TEXT
echo "$X + $Y = $Z"
echo “ ”
echo "Example of IF statement"
if [ $X -lt $Y ]
then
echo "$X is less than $Y"
fi
Save your changes and exit VIM and then run the script: ./variables.sh
If everything works, proceed to the next step (you don’t need to show your instructor)
Now, let’s add an “else” statement to your variables.sh file. An else statement will do something
else (like print a different string of text) if the if-then statement that came before it is not true.
variables.sh
#!/bin/bash
#Simple sum
TEXT="This script makes a sum of two numbers using Arithmetic Expansion with
the format: result=\$((n1+n2))"
X=289
Y=131
Z=$((X+Y))
echo $TEXT
echo "$X + $Y = $Z"
echo
echo "Example of IF statement"
if [ $X -lt $Y ]
then
echo "$X is less than $Y"
else
echo “$X is NOT less than $Y”
fi
1. Create a script called contacts.sh and add the code below (next page too).
contacts.sh
#!/bin/bash
#Simple telephone list stored in contacts.txt file
CONTACTS=~/contacts.txt
# At least two parameters needed so $# is not less than 2
if [ $# -lt 2 ] # -lt means “less than”
then
echo "Error: Not enough parameters given."
exit 1 #Exit with error code
fi
#If keyword "add" was used
if [ $1 = "add" ] # "=" is used to compare string values
then
shift #Remove "add" from the parameters list
echo "$*" >> $CONTACTS
echo "$* added to database."
exit 0 #Exit with normal code
fi
#If keyword "find" was used
if [ $1 = "find" ]
then
shift #Remove "find" from the parameters list
grep -q $* $CONTACTS #Search quietly the contacts
if [ $? -ne 0 ]
then
echo "$* is not in the database!"
exit 1
else
echo "Found \"$*\" in the database."
exit 0 #Exit with normal code
fi
fi
NOTE: do NOT put “ANYNAME” etc. – use specifics (i.e. ./contacts.sh add joe 905-555-1212
joe@yahoo.com ). You also cannot use brackets for the area code (i.e. “(905) )
3. To find ANY specific entry (name, number, e-mail) for an existing contact, type:
./contacts.sh find VALUE (again, don’t type “VALUE”...)
NOTE: (ANYNAME, ANYNUMBER, and ANYEMAIL are input parameters for the script and
VALUE is any search term as an input parameter. Remember, values are case-sensitive.)
After everything else has been completed, create a script while.sh that....does something (?)
while.sh
#!/bin/bash
echo "Example of WHILE statement"
COUNTER=0
while [ $COUNTER -ge 0 ]
do
echo $COUNTER
COUNTER=$((COUNTER+1))
done
Once you’ve stopped the script, take a screenshot of your entire Linux VM window (NOT the
whole desktop!!!!!) to attach to the Dropbox Questions