Nothing Special   »   [go: up one dir, main page]

Lab 05 - Scripting (W2022)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Lab 5.

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

Deliverables and rubrics


 Lab 5 practical is due by the end of your lab session
 Lab 5 questions are due by MIDNIGHT (EST) on the same day as your lab

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.

NOTE. Linux syntax is case-sensitive, which means that the command:


touch new New nEw neW NEW
will not throw an error and will indeed create five different files

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)

PART A. Basic Shell Commands


Activity 1. Login to your Ubuntu Server and enter the following commands in the shell.
1. Create file ‘testfile‘: touch testfile
2. Create folder ‘testfolder‘: mkdir testfolder
3. Overwrite testfile: echo "This is the text inside testfile">testfile
4. Display the contents of testfile: cat testfile
5. Append text to testfile: echo "This is the appended line inside testfile">>testfile
6. Display the contents of testfile: cat testfile
7. Copy testfile to backupfile: cp testfile backupfile
8. Display the contents of backupfile: cat backupfile
9. Move testfile inside testfolder: mv testfile testfolder
10. List testfolder contents in long form using: ls -l testfolder
11. Find lines containing the word “bash” inside /etc/passwd and append those results to
the newfile:
grep bash /etc/passwd >> newfile
12. Display the contents of newfile: cat newfile
13. Find occurrences of “core” in the system using:
find / -name core
As you can see, there is a lot information sent to the screen and it is difficult to follow
as successful hits and unsuccessful errors (Permission denied) results are mixed
14. Send the successful hits (STDOUT or 1) to file “hits” and errors (STDERR or 2) to the file
“errors” using:
find / -name core 1>hits 2>errors
There is no output to the screen as we are redirecting STDOUT and STDERR
15. Check the contents of the hits file with cat hits
16. Check the contents of the errors file with cat errors
17. If everything worked, go on to Part B

Part B. Basic Scripting


In the previous exercises, we entered the shell commands line by line. Shell commands can
also be stored in files and executed whenever convenient in form of bash scripts. Identifying
tasks that can be automated with scripts frees time to focus on more critical activities such as
security or process optimization.
The first line of a Shell script must always include the expression #!/bin/bash (also called a
“shebang”). This is because there can be different shells running in the Linux system and this
line ensures that the script will be run using the Bash Shell instead of any other which might
differ slightly in commands or parameters.

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)

PART C. Advanced Scripting

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)

TEXT="Text expressions are enclosed in quotation marks"


NUMBER=50 #Numbers are assigned directly and don’t need quotes

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.

Script parameter1 parameter2 parameter3


refers to: [$0] [$1] [$2] [$3]

Where $0 refers to scriptName, $1 to parameter1, $2 to parameter2 and $3 to parameter3.


Other parameters passed to the shell are: $* which provides the complete string of parameters
and $# which provides the number of parameters entered by the user and $? Which receives the
exit status of the last executed command (0 for success, any other value for error).

Activity 2. Create a script that multiply two numbers entered by the user.

1. Create the script input.sh with vim input.sh


2. Add the shebang in the first line: #!/bin/bash
3. Under shebang, type: RESULT=$(($1 * $2))
4. Under that, display the result: echo "$1 * $2 = $RESULT"
5. Write and quit VIM editor using :wq
6. Change the permissions in the file to make it executable: chmod +x input.sh
7. Multiply 5 by 4 typing: ./input.sh 5 4
8. Clear your screen with the command clear
9. Run the same command as in step 7. but use two different values (i.e. NOT “5” and “4”)
10. Take a screenshot showing the new calculation worked, and attach it in the Dropbox
Questions Section
The following section will discuss “if-then” statements and prepare you for the final activity
(creating the contacts.sh script). If-then statements use conditions to change what the script
does (if a condition is met, then do something). Remember that if-then statements always
START with if and CLOSE (end) with fi.

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

[ operand1 operator operand2 ]

Some very useful test operators are the following:


❏ = the operands are equal and they are strings
❏ != the opposite of = (not equal), for strings (exclamation point always means “not”)
❏ -eq the operands are integers and they are equal
❏ -ne the opposite of -eq, for integers
❏ -lt the operand1 is less than operand2 and they are integers
❏ -gt the operand1 is greater than operand2 and they are integers
❏ -le the operand1 is less than or equal to operand2 and they are integers
❏ -ge the operand1 is greater than or equal to operand2 and they are integers

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.

1. Open the variables.sh in vim editor


2. Change the values of X and Y so they are reversed (X=289, Y=131)
3. Add the else and echo line, as shown in blue below

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

4. Exit variables.sh and run it.


5. If everything works (review the code to see the logic), continue on to Activity 3. (you do
not need to show your instructor the output)

PART D – CONTACT LIST

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

2. Now run the script and add a new contact by typing:


./contacts.sh add ANYNAME ANYNUMBER ANYEMAIL

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

4. If everything works, add 3 more contacts to your database.


5. Clear your screen with clear
6. Type cat contacts.txt to list all of the contacts you entered in the database
7. Run the script to find any ONE of the values you entered (name, phone #, email)
8. Take a screenshot of the (combined) output from both the cat contacts.txt and find
<value> commands to insert in the Dropbox Questions section

LAST ACTIVITY - The ? Statement

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

Run the script and see what happens.


Now, how do you stop it and return to the command prompt?!? 

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

You might also like