0% found this document useful (0 votes)
21 views49 pages

05 Bash Script Intro

The document provides an overview of basic bash scripting concepts including: - Creating executable shell scripts with the .sh extension - Storing values in variables and referencing variables - Using conditionals like if/then statements and checking command exit codes - Passing arguments to scripts and accessing them as $1, $2, etc. - Examples are provided for simple scripts that output greetings, find files, and check if a user exists.

Uploaded by

Dinuka Chanaka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views49 pages

05 Bash Script Intro

The document provides an overview of basic bash scripting concepts including: - Creating executable shell scripts with the .sh extension - Storing values in variables and referencing variables - Using conditionals like if/then statements and checking command exit codes - Passing arguments to scripts and accessing them as $1, $2, etc. - Examples are provided for simple scripts that output greetings, find files, and check if a user exists.

Uploaded by

Dinuka Chanaka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Bash script:

introduction
NB: all examples use emulator in
Linux essentials, not Linux
unhatched

files and directories differ in each


course
Recap week 4
Commands

• what does su do?


• what does sudo do?
• what does whoami do?
• what is stored in following files:
• /etc/passwd
• /etc/shadow
• which command is used to delete a group?
• which command is used to create a user?
• which option is used to create the user's home directory?
Permissions

• what does -rwx------ mean?


• what does -rw-rw-r-- mean?

• what do the following do?


• chmod o+r
• chmod a=r
• chmod ug+x
• chmod 777
• chmod 754
To be covered
(Ess 11)
• most of module 11 - basic scripting (but not loops!)
basic scripting if statement case statement demos
variables evaluate exit codes hello.sh
environment variables compare numbers greetings.sh
compare strings whoareyou.sh
PATH variable check file existence, file findfiles.sh
quotes permissions
complex conditions checkuser.sh
exit codes checkargs.sh
arguments checkusername.sh
deletefile.sh
checkstaff.sh
Basic scripting
(Ess 11)
Basic scripting

• a script is simply executable commands stored in a file


• we will be writing Bash script
• files stored with a .sh extension
• sh indicates a shell script
• file needs to be executable to run
• execute permission
• NB: all the following examples could be run at the command
prompt, though we will put them in a file
Benefits of scripts

• automate tasks
• reduce risk of errors
• combine sequences of commands
into a single command
• share procedures between users
• provide controlled access for users
• rapid prototyping
Available shell options

• /etc/shells specifies which shells are available on a distro


cat /etc/shells

will use
w e
s h which
a
/bin/b efault
d
is the

• where else have we seen /bin/bash?


Recap nano

• text editor
• arrow keys to move around
• delete and backspace to
delete text
• context-sensitive options at
bottom of screen
• CTRL&X to quit
• prompted to save file
Variables
Variables
(Ess 11.4.1)

e spaces
• variables store values within a script or terminal session
there must not b
v aria ble n ame, = and
be tw een
e w ill be an error
• to declare a variable with the value "Jan"
v a lue o r th er
name="Jan"

eter • to reference a variable


$ informs interpr
able
to substitute vari
with its value
$name

ded
quotes are not nee • to reference a variable inside a string
t but
in echo statemen
ity
improve readabil echo "My name is $name"
Environment variables

• system automatically creates environment variables when new shell


opened
• uppercase names by convention
• available system-wide
• HOME
• PATH
• environment variables are handled in same way as any other variable
An aside about PATH variable (1 of 2)

• PATH variable contains a list of directories the shell searches for commands
• directories are separated by :
• paths searched in order they are listed

• if command not found in any directory, shell will output "command not found"
• normally due to invalid command
• but can be directory containing command not in PATH variable
An aside about PATH variable (2 of 2)

• can add directories containing any custom software to the PATH variable
• must append or prepend values to PATH variable, not overwrite it
• otherwise will lose access to existing commands
Quotes
Quotes
(Ess 5.6)

• quotes cause the enclosed text to be treated differently


• to output:

My name, Jan, is stored in $name


It is currently Fri Nov 4 13:30:12 UTC 2022

• assign name="Jan"
Double quotes
(Ess 5.6)

• double quotes allow variable and command substitution


• ie. they are evaluated before being output
echo "My name, $name, is stored in $name"
echo "It is currently $(date)"

commands must be
enclosed in parentheses

echo "My name, $name, is stored in \$name"

es variable
backslash overrid
bstitution
and command su
Single quotes
(Ess 5.6)

• single quotes prevent variable and command substitution


echo 'My name, $name, is stored in $name'
echo 'It is currently $(date)'
Let's code!
Development steps

• TO DO:
• create directory called week5 create file
• change to week5 directory
• how?

make file
• create new file with sh as file extension executable
• how? sh indicates that it
is a shell script
• make file executable
• how?
run file
• run file
• using ./ followed by name of file
DEMO: first script (1 of 3)
(Ess 11.2)

• script to output "Hello World!" to the screen

• create a file called hello.sh


• add code to script
#!/bin/bash
echo 'Hello World!'

• save file
DEMO: first script (2 of 3)
(Ess 11.2)

• run the executable file (script) from the current directory


./hello.sh

why is there
• check permissions with ls -l an error?

what does
this mean?
DEMO: first script (3 of 3)
(Ess 11.2)

• change permissions
chmod u+x hello.sh

what does
this do?
• run script
./hello.sh

./ runs named script


in current directory
Using variables
DEMO: saving results in variables

• store username and time in variables, then output them in a greeting


• create a file called greetings.sh
#!/bin/bash see link for options
username=$(whoami) for date formatting
currenttime=$(date +%H:%M)
echo "Hello ${username}, it is ${currenttime}"

• change permissions and run file


DEMO: getting input from user

• prompt user to enter name, then output a personalised greeting


• create a file called whoareyou.sh

#!/bin/bash
echo -n "What is your name? " -n in an echo statement
read name prevents newline at end
echo "Hello $name!"

• change permissions and run file


DEMO: using variables in commands

• find all files of specified type in /Documents


• create a file called findfiles.sh
#!/bin/bash
echo -n "What file extension do you want to look for? "
read extension
find ~/Documents -name "*.$extension"

• change permissions and run file


Conditionals
Exit codes

• commands return an exit code to indicate success of operation


• 0 represents no error
• any other value (1 - 255) represents an error defined by that particular command
• exit code stored in the $? environment variable
success failure
if statement
(Ess 11.4.2)

• perform action based on condition can put newline


instead of semicolon
• possible conditions:
• evaluate return value of a command (0 for success)
• compare numbers
• compare strings if condition1; then
• check file existence, file permissions # do this if condition1
is true
elif condition2; then
# do this if condition2
else
# otherwise do this
fi
Passing arguments

• we have used many commands that accept arguments


• which commands?
• argument values are automatically available within the script
• $0 name of the script
• $1 value of the first parameter
• $2 value of the second parameter
• ...
• $# number of parameters passed
• $@ all parameters passed
DEMO: evaluate exit code of command

• check whether the value passed as a parameter exists in /etc/passwd


• create a file called checkuser.sh

#!/bin/bash -q option will prevent


if grep -q $1 /etc/passwd; then output being displayed
echo "$1 is a current user"
else
echo "$1 is not a current user"
fi

• change permissions
• run file

do not forget to
pass a parameter
Numeric comparisons

• numeric comparisons are enclosed within [ ]


• numbers are compared using symbolic expressions
-eq must include a space
-ge after [ and before ]

-gt
[ is a com
mand,
-le equivalent
to test, wh if [ $age -eq 21 ]
requires a ich
-lt matching if test $age -eq 21
closing squ
are bracke
-ne t

r e e q uiv alent
these a
DEMO: compare numbers

• check number of arguments provided is greater than 0


• create a file called checkargs.sh

#!/bin/bash must include a space


after [ and before ]

if [ $# -eq 0 ]; then
echo "You must provide at least 1 argument"
fi

• change permissions
• run file
String comparisons

• string comparisons are enclosed within [ ]


• comparisons are case-sensitive
• strings are compared using equality symbols returns false
=
!=
= behaves if [ 01 = 1 ]
differently
to -eq if [ 01 -eq 1 ]

rue
returns t
DEMO: compare strings

• check if user enters correct username


• create a file called checkusername.sh

#!/bin/bash
echo -n "What is your username? "
read name
if [ $USER = $name ]; then
echo "Correct username"
else
echo "Incorrect username"
fi
Complex conditions

• can combine the result of separate tests using Boolean operators


&& all parts must be true
|| at least one part must be true
! negate the boolean value

if [ 01 = 1 ] && [ 01 -eq 1 ]

if [ 01 = 1 ]; then
if [ 01 -eq 1 ]; then
#executed if both true
File existence and permissions

• several options are provided to check file existence and permissions:


-e file true if file exists
-f file true if file is a regular file
-d file true if file is a directory
-s file true if file has non-zero size (ie has content)
-r file true if file is readable
-w file true if file is writable [ -f Documents/words ]
echo $?
-x file true if file is executable
Returning exit codes

• in addition to checking exit code from other commands, can also return
exit code from scripts

exit 1
DEMO: check file existence (1 of 3)

• prompt the user for a filename and delete the file if it is empty, outputting
suitable messages if the file does not exist or is not empty and returning exit
codes
• create an empty file called empty.txt
• create a file called notempty.txt containing "This file is not
empty"
• how?

• create new file called deletefile.sh to contain script


#!/bin/bash

echo -n "Which file do you want to delete? "


DEMO: check read file

file existence if [ ! -f $file ]; then


(2 of 3) echo "$file does not exist"
exit 1
elif [ -s $file ]; then
echo "cannot delete $file as it is not empty"
exit 2
else
rm $file
echo "$file has been deleted"
exit 0
fi
DEMO: check
file existence
(3 of 3)
Case statement

• case... esac is alternative to multiple elif clauses within if...


else... fi statement
• multiple cases
• statements associated with the first matching case are executed
• ) delimits end of values for a case
• | used to separate alternative values for a case
• * default case which is executed if no other cases match
• equalivalent to else
• ;; ends the statements to be executed if the case is true
• ;& allows fall-through so that following cases may also match
#!/bin/bash
what do
echo -n "Staff name? " es this
script d
read name o?
DEMO: check case $name in
strings using Fiona)

case echo "Module leader"


;&

(1 of 2) Jan)
echo "Delivers lectures and tutorials"
;;
Dan|Russell)
echo "Tutorials"
;;
*)
echo "Not a lecturer on WDOS"
m o re
is i t
esac
dab le?
rea
DEMO: check
strings using
case
(2 of 2)
• basic scripting • programs
• variables • hello.sh
• environment variables • greetings.sh
What we •

PATH variable
quotes


whoareyou.sh
findfiles.sh
have covered • exit codes • checkuser.sh
• arguments • checkargs.sh
• checkusername.sh
• deletefile.sh
• if statements • checkstaff.sh
• evaluate return value of command
• compare numbers
• compare strings
• check file existence, file
permissions
• complex conditions

• case statement
Any questions?

You might also like