shell programming, or scripting
DESCRIPTION
Shell Programming, or Scripting. Shirley Moore CPS 5401 Fall 2013 www.cs.utep.edu/svmoore svmoore@ utep.edu August 29, 2013. What is a Shell Script?. Normally shells are interactive – a shell accepts a command from you and executes it. - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/1.jpg)
1
Shell Programming, or Scripting
Shirley MooreCPS 5401 Fall 2013
www.cs.utep.edu/[email protected]
August 29, 2013
![Page 2: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/2.jpg)
2
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• loops
• Shell scripts are useful for automating repetitive workflows.
• Shell scripting is fun!
![Page 3: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/3.jpg)
3
Disadvantages of Shell Scripting
• Incompatibilities between different platforms• Slow execution speed• A new process is launched for almost every
shell command executed.
![Page 4: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/4.jpg)
4
Learning Objectives
• After completing this lesson, you should be able to – Explain the basics of Linux shell scripting– Write shell scripts and use them to save time– Customize your shell startup files
• We will use the Bash shell
![Page 5: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/5.jpg)
5
Bash initialization and startup files1. /etc/profile – the systemwide initialization file, executed for
login shells2. /etc/bash.bashrc – the systemwide per-interactive-shell
startup file– may not exist or may not get sourced– might be named /etc/bashrc
3. /etc/bash.logout – systemwide login shell cleanup file, executed when a login shell exits
4. $HOME/.bash_profile – your personal initialization file5. $HOME/.bashrc – your individual per-interactive-shell startup
file6. $HOME/.bash_logout – your login shell cleanup file7. $HOME/.inputrc – individual readline initialization file
![Page 6: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/6.jpg)
6
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.bashrc
![Page 7: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/7.jpg)
7
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.
![Page 8: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/8.jpg)
8
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.sh
• Execute the file$ ./hello.sh
![Page 9: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/9.jpg)
9
Shell Comments
• Example:#!/bin/bash# A Simple Shell Script To Get Linux Network Information# Vivek Gite - 30/Aug/2009echo "Current date : $(date) @ $(hostname)"echo "Network configuration"/sbin/ifconfig
• Lines beginning with # are ignored by Bash• Explanatory text about the script• Make the script easier to understand and maintain
![Page 10: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/10.jpg)
10
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
![Page 11: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/11.jpg)
11
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”
![Page 12: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/12.jpg)
12
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 $myvar
![Page 13: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/13.jpg)
13
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
![Page 14: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/14.jpg)
14
Arithmetic Operations
• Tryecho $((10 + 5))
• Create and run a shell script called add.sh:#!/bin/bashread -p “Enter first number : “ xread -p “Enter second number : “ yans=$(( x + y ))echo "$x + $y = $ans"
![Page 15: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/15.jpg)
15
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
![Page 16: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/16.jpg)
16
Conditional Execution• Test command
test –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
![Page 17: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/17.jpg)
17
If statement
• Create and execute a file named number.sh:#!/bin/bashread -p "Enter # 5 : " numberif test $number == 5thenecho "Thanks for entering # 5"fiif test $number != 5thenecho "I told you to enter # 5. Please try again."fi
![Page 18: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/18.jpg)
18
If statement (2)
• Create and execute a file named number.sh:#!/bin/bashread -p "Enter # 5 : " numberif test $number == 5thenecho "Thanks for entering # 5”elseecho "I told you to enter # 5. Please try again."fi
![Page 19: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/19.jpg)
19
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 ]thenecho "$n is negative."elif [ $n -eq 0 ]thenecho "$n is zero.”fi
![Page 20: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/20.jpg)
20
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.
![Page 21: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/21.jpg)
21
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.
![Page 22: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/22.jpg)
22
Exit Command• exit N
– The 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 0
![Page 23: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/23.jpg)
23
Exit Status of a Command
• Create and run the following script called finduser.sh#!/bin/bash# set varPASSWD_FILE=/etc/passwd# get user nameread -p "Enter a user name : " username# try to locate username in in /etc/passwdgrep "^$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
![Page 24: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/24.jpg)
24
Command arg processing using case#!/bin/bash# casecmdargs.shOPT=$1 # optionFILE=$2 # filename# test command line args matchingcase $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
![Page 25: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/25.jpg)
25
For loop
#!/bin/bash# testforloop.shfor i in 1 2 3 4 5do echo "Welcome $i times."done
![Page 26: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/26.jpg)
26
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
![Page 27: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/27.jpg)
27
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 $ndone
![Page 28: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/28.jpg)
28
Until loop
#!/bin/bashuntil.shi=1until [ $i -gt 6 ]do echo "Welcome $i times." i=$(( i+1 ))done
![Page 29: Shell Programming, or Scripting](https://reader038.vdocuments.net/reader038/viewer/2022102810/56816935550346895de08ead/html5/thumbnails/29.jpg)
29
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.