Download presentation
Presentation is loading. Please wait.
Published byToby Cody Marshall Modified over 9 years ago
1
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall 2013 www.cs.utep.edu/svmoore svmoore@utep.edu August 29, 2013 1
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! 2
3
Disadvantages of Shell Scripting Incompatibilities between different platforms Slow execution speed A new process is launched for almost every shell command executed. 3
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 4
5
Bash initialization and startup files 1./etc/profile – the systemwide initialization file, executed for login shells 2./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 file 5.$HOME/.bashrc – your individual per-interactive-shell startup file 6.$HOME/.bash_logout – your login shell cleanup file 7.$HOME/.inputrc – individual readline initialization file 5
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 6
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. 7
8
Try this Example Save the following into a file named hello.sh and close the file: #!/bin/bash echo “Hello, World!” echo “Knowledge is power.” Make the file executable $ chmod +x hello.sh Execute the file $./hello.sh 8
9
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/ifconfig Lines beginning with # are ignored by Bash Explanatory text about the script Make the script easier to understand and maintain 9
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 10
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” 11
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 12
13
Getting User Input Create a script called greet.sh as follows: #!/bin/bash read -p "Enter your name : " name echo "Hi, $name. Let us be friends!" Save and close the file. Run it as follows: chmod +x greet.sh./greet.sh 13
14
Arithmetic Operations Try echo $((10 + 5)) Create and run a shell script called add.sh: #!/bin/bash read -p “Enter first number : “ x read -p “Enter second number : “ y ans=$(( x + y )) echo "$x + $y = $ans" 14
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 15
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 16
17
If statement Create and execute a file named number.sh: #!/bin/bash read -p "Enter # 5 : " number if test $number == 5 then echo "Thanks for entering # 5" fi if test $number != 5 then echo "I told you to enter # 5. Please try again." fi 17
18
If statement (2) Create and execute a file named number.sh: #!/bin/bash read -p "Enter # 5 : " number if test $number == 5 then echo "Thanks for entering # 5” else echo "I told you to enter # 5. Please try again." fi 18
19
Nested If Create and execute numest.sh: #!/bin/bash read -p "Enter a number : " n if [ $n -gt 0 ]; then echo "$n is positive." elif [ $n -lt 0 ] then echo "$n is negative." elif [ $n -eq 0 ] then echo "$n is zero.” fi 19
20
Command-line Arguments Create and run the following script called cmdargs.sh giving it some arguments: #!/bin/bash echo "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. 20
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. 21
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/bash echo "This is a test." # Terminate our shell script with success message exit 0 22
23
Exit Status of a Command Create and run the following script called finduser.sh #!/bin/bash # set var PASSWD_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 status status=$? if test $status -eq 0 then echo "User '$username' found in $PASSWD_FILE file." else echo "User '$username' not found in $PASSWD_FILE file." fi 23
24
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 24
25
For loop #!/bin/bash # testforloop.sh for i in 1 2 3 4 5 do echo "Welcome $i times." done 25
26
Nested for loop #!/bin/bash # chessboard.sh – script to display a chessboard on the screen for (( 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 26
27
While loop #!/bin/bash # while.sh # set n to 1 n=1 # continue until $n equals 5 while [ $n -le 5 ] do echo "Welcome $n times." n=$(( n+1 )) # increments $n done 27
28
Until loop #!/bin/bash until.sh i=1 until [ $i -gt 6 ] do echo "Welcome $i times." i=$(( i+1 )) done 28
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. 29
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.