290 likes | 494 Views
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.
E N D
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. • 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!
Disadvantages of Shell Scripting • Incompatibilities between different platforms • Slow execution speed • A new process is launched for almost every shell command executed.
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
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 sourced • might 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
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
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.
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 +xhello.sh • Execute the file $ ./hello.sh
Shell Comments • Example: #!/bin/bash # A Simple Shell Script To Get Linux Network Information # VivekGite - 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
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
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”
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
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 +xgreet.sh ./greet.sh
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"
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 +xvarcheck.sh ./varcheck.sh /home ./varcheck.sh
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
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
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
Nested If • Create and execute numest.sh: #!/bin/bash read -p "Enter a number : " n if [ $n -gt 0 ]; then echo "$nis positive." elif [ $n -lt 0 ] then echo "$nis negative." elif [ $n -eq 0 ] then echo "$n is zero.” fi
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.
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.
Exit Command • exit N • The exit statement is used to exit fromashell 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
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
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
For loop #!/bin/bash # testforloop.sh for i in 1 2 3 4 5 do echo "Welcome $i times." done
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
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
Until loop #!/bin/bash until.sh i=1 until [ $i -gt 6 ] do echo "Welcome $i times." i=$(( i+1 )) done
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.