Shirley Moore CPS 5401 Fall 2013 wwwcsutepedusvmoore svmoore utepedu August 29 2013 1 What is a Shell Script Normally shells are interactive a shell accepts a command from you and executes it ID: 583923
Download Presentation The PPT/PDF document "Shell Programming, or Scripting" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Shell Programming, or Scripting
Shirley MooreCPS 5401 Fall 2013www.cs.utep.edu/svmooresvmoore@utep.eduAugust 29, 2013
1Slide2
What is a Shell Script?
Normally shells are interactive – a shell accepts a command from you and executes it.You can store a sequence of commands in a text file, called a shell script, and tell the shell to execute the file.In addition to commands, you can use functions
control flow statements
if..then..else
loopsShell scripts are useful for automating repetitive workflows.Shell scripting is fun!
2Slide3
Disadvantages of Shell Scripting
Incompatibilities between different platformsSlow execution speedA new process is launched for almost every shell command executed.3Slide4
Learning Objectives
After completing this lesson, you should be able to Explain the basics of Linux shell scriptingWrite shell scripts and use them to save timeCustomize your shell startup filesWe will use the Bash shell
4Slide5
Bash initialization and startup files
/etc/profile – the systemwide initialization file, executed for login shells/etc/bash.bashrc – the
systemwide
per-interactive-shell startup file
may not exist or may not get sourcedmight be named /etc/bashrc
/etc/
bash.logout
–
systemwide
login shell cleanup file, executed when a login shell exits
$HOME/.
bash_profile
– your personal initialization file
$HOME/.bashrc – your individual per-interactive-shell startup file$HOME/.bash_logout – your login shell cleanup file$HOME/.inputrc – individual readline initialization file
5Slide6
Bash init and startup files (2)
A login shell calls the following when a user logs in/etc/profile runs first when a user logs in$HOME/.bash_profile runs second$HOME/.bash_profile calls $HOME/.bashrc
, which calls /etc
/
bash.bashrc6Slide7
To Create a Shell Script
Use a text editor such as vi to create the file.Save and close the file.Make the file executable.Test the script.7Slide8
Try this Example
Save the following into a file named hello.sh and close the file:#!/bin/bashecho “Hello, World!”echo “Knowledge is power.”Make the file executable$
chmod
+
x hello.shExecute the file$ ./
hello.sh
8Slide9
Shell Comments
Example:#!/bin/bash# A Simple Shell Script To Get Linux Network Information# Vivek Gite - 30/Aug/2009
echo "Current date : $(date) @ $(hostname)"
echo "Network configuration"
/sbin/ifconfigLines beginning with # are ignored by Bash
Explanatory text about the script
Make the script easier to understand and maintain
9Slide10
Formatted Output with printf
Use the printf command to format output to appear on the screen (similar the C printf() )Example:printf “%s\n” $PATH
10Slide11
Quoting
Try these$ echo $PATH$ echo “$PATH”$ echo ‘$PATH’$ echo \$PATH$ echo /etc/*.conf$ echo “/etc/*.conf”
$ echo ‘/etc/*.conf’
$ echo “PATH is $PATH”
$ echo “PATH is \$PATH”
11Slide12
Export and Unset
The export builtin exports environment variables to child processes.Try the following:$ myvar=“Hello, world”
$ echo $
myvar
$ export myvar2=“Hello, world2”$ echo $myvar2$ bash$ echo $
myvar
$ echo $myvar2
$ exit
$ export
$ echo $
myvar
$ unset
myvar
$ echo $myvar12Slide13
Getting User Input
Create a script called greet.sh as follows:#!/bin/bashread -p "Enter your name : " nameecho "Hi, $name. Let us be friends!"Save and close the file. Run it as follows:chmod
+
x
greet.sh./greet.sh
13Slide14
Arithmetic Operations
Tryecho $((10 + 5))Create and run a shell script called add.sh:#!/bin/bashread -p “Enter first number : “
x
read -
p “Enter second number : “ yans=
$((
x
+
y
))
echo "$
x
+ $
y = $ans"14Slide15
Variable Existence Check
Create a shell script called varcheck.sh:#!/bin/bash# varcheck.sh: Variable sanity check with :?path=${1:?Error command line argument not passed}
echo "Backup path is $path."
echo "I'm done if \$path is set
.”Run it as follows:chmod +x
varcheck.sh
./
varcheck.sh
/home
./
varcheck.sh
15Slide16
Conditional Execution
Test commandtest –f /etc/autofs.conf && echo “File autofs.conf found” || echo “File autofs.conf not found”
Can also use [ ]
[ -
f /etc/autofs.conf ] && echo “file autofs.conf found” || echo “file
autofs.conf
not found”
For more information:
$ man test
command1 && command2 – execute command2 if command1 is successful
command1 || command2 – execute command2 if command1 is not successful
16Slide17
If statement
Create and execute a file named number.sh:#!/bin/bashread -p "Enter # 5 : " numberif test $number == 5then
echo "Thanks for entering # 5"
fi
if test $number != 5thenecho "I told you to enter # 5. Please try again."
fi
17Slide18
If statement (2)
Create and execute a file named number.sh:#!/bin/bashread -p "Enter # 5 : " numberif test $number == 5then
echo "Thanks for entering #
5”
elseecho "I told you to enter # 5. Please try again."fi
18Slide19
Nested If
Create and execute numest.sh:#!/bin/bashread -p "Enter a number : " nif [ $n
-
gt
0 ]; thenecho "$n is positive."elif [ $
n
-
lt
0 ]
then
echo "$
n
is negative."elif [ $n -eq 0 ]thenecho "$n is zero.”fi19Slide20
Command-line Arguments
Create and run the following script called cmdargs.sh giving it some arguments:#!/bin/bashecho "The script name : $0"echo "The value of the first argument to the script : $1"echo "The value of the second argument to the script : $2"
echo "The value of the third argument to the script : $3"
echo "The number of arguments passed to the script : $#"
echo "The value of all command-line arguments (\$* version) : $*"echo "The value of all command-line arguments (\$@ version) : $@”
Try adding IFS=“,” as the second line of the script.
20Slide21
Shell Parameters
All command line parameters or arguments can be accessed via $1, $2, $3,..., $9.$* holds all command line parameters or arguments.$# holds the number of positional parameters.$- holds flags supplied to the shell.
$
? holds the return value set by the previously executed command.
$$ holds the process number of the shell (current shell).$! hold the process number of the last background command.
$
@ holds all command line parameters or arguments.
21Slide22
Exit Command
exit NThe exit statement is used to exit from a shell script with a status of N.Use the exit statement to indicate successful or unsuccessful
shell script termination
.
The value of N can be used by other commands or shell scripts to take their own action.If N is omitted, the exit status is that of the last command executed.
Use
the exit statement to terminate
a shell
script upon an error.
N
set to 0 means normal shell exit.
Create
a shell script called exitcmd.sh:#!/bin/bashecho "This is a test."# Terminate our shell script with success messageexit 022Slide23
Exit Status of a Command
Create and run the following script called finduser.sh#!/bin/bash# set varPASSWD_FILE=/etc/
passwd
# get user name
read -p "Enter a user name : " username# try to locate username in in /etc/
passwd
grep
"^$username" $PASSWD_FILE > /dev/null
# store exit status of
grep
# if found
grep
will return 0 exit
stauts# if not found, grep will return a nonzero exit statusstatus=$?if test $status -eq 0thenecho "User '$username' found in $PASSWD_FILE file."elseecho "User '$username' not found in $PASSWD_FILE file."
fi
23Slide24
Command
arg processing using case#!/bin/bash# casecmdargs.sh
OPT=$1
# option
FILE=$2 # filename# test command line args matching
case $OPT in
-
e
|-E)
echo
"Editing
file $2.
.."
# make sure filename is passed else an error displayed [ -z $FILE ] && { echo "File name missing"; exit 1; } || vi $FILE ;; -c|-C)
echo
"Displaying
file $2.
.."
[
-
z
$FILE ] && { echo "File name missing"; exit 1; } ||
cat
$FILE
;;
-
d
|-D)
echo
"Today is $(date)"
;
;
*
)
echo
"Bad argument!"
echo
"Usage: $0 -
ecd
filename"
echo
" -
e
file : Edit file."
echo
" -
c
file : Display file."
echo
" -
d
: Display current date and time."
;;
esac
24Slide25
For loop
#!/bin/bash# testforloop.shfor i in 1 2 3 4 5do echo
"Welcome $
i
times."done25Slide26
Nested for loop
#!/bin/bash# chessboard.sh – script to display a chessboard on the screenfor (( i = 1; i <= 8;
i
++ ))
### Outer for loop ###do for (( j = 1 ;
j
<= 8;
j
++ ))
### Inner for loop ###
do
total
=
$(( $i + $j)) # total tmp=$(( $total % 2)) # modulus # Find out odd and even number and change the color # alternating colors using odd and even number logic
if
[ $
tmp
-
eq
0 ];
then
echo
-
e
-
n
"\033[47m "
else
echo
-
e
-
n
"\033[40m "
fi
done
echo ""
#### print the new line ###
done
26Slide27
While loop
#!/bin/bash# while.sh# set n to 1n=1
# continue until $
n
equals 5while [ $n -le 5 ]do echo
"Welcome $
n
times."
n
=
$(( n+1 ))
# increments $
ndone27Slide28
Until loop
#!/bin/bashuntil.shi=1until [ $i -gt 6 ]
do
echo
"Welcome $i times." i
=
$(( i+1 ))
done
28Slide29
Exercises
Write a shell script that counts the number of files in each of the sub-directories of your home directory. Write a shell script that accepts two directory names as arguments and deletes those files in the first directory that have the same names in the second directory.
29