1 / 29

Shell Programming, or Scripting

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.

lavi
Télécharger la présentation

Shell Programming, or Scripting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Shell Programming, or Scripting Shirley Moore CPS 5401 Fall 2013 www.cs.utep.edu/svmoore svmoore@utep.edu August 29, 2013

  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!

  3. Disadvantages of Shell Scripting • Incompatibilities between different platforms • Slow execution speed • A new process is launched for almost every shell command executed.

  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

  5. 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

  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

  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.

  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 +xhello.sh • Execute the file $ ./hello.sh

  9. 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

  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

  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”

  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

  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 +xgreet.sh ./greet.sh

  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"

  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 +xvarcheck.sh ./varcheck.sh /home ./varcheck.sh

  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

  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

  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

  19. 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

  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.

  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.

  22. 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

  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

  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

  25. For loop #!/bin/bash # testforloop.sh for i in 1 2 3 4 5 do echo "Welcome $i times." done

  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

  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

  28. Until loop #!/bin/bash until.sh i=1 until [ $i -gt 6 ] do echo "Welcome $i times." i=$(( i+1 )) done

  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.

More Related