UNIX Shell Scripting

Ken Steube
UCSD Extension
steube@sdsc.edu


This course will teach you to write Bourne shell Scripts. We will then learn about C shell scripts, and will have a brief introduction to perl as well. Scripting skills have many applications, including:

  • Ability to automate tasks, such as
    • Backups
    • Administration tasks
    • Periodic operations on a database via cron
    • Any repetetive operations on files
  • Increase your general knowledge of UNIX
    • Use of environment
    • Use of UNIX utilities
    • Use of features such as pipes and I/O redirection

Our course syllabus is available on-line.

Some tips on working in SDSC's training lab are available.

I also have a comparison between features of the C shell and Bourne shell.

To connect to the SDSC lab computers from home or work you will need to use ssh instead of telnet or rlogin. Be sure to use an implementation of SSH that uses protocol version 1.0.

There is a free ssh program available from PuTTY.

SSH for UNIX is available from SSH.

For this class you will need a data file called last.out. To get this file, put the mouse over the blue text, press the right mouse button, and select "Save link as".

Table of Contents:

  1. Review of a few Basic UNIX Topics (Page 1)
  2. Storing Frequently Used Commands in Files: Shell Scripts (Page 6)
  3. More on Using UNIX Utilities (Page 9)
  4. Performing Search and Replace in Several Files (Page 11)
  5. Using Command-line Arguments for Flexibility (Page 14)
  6. Using Functions (Page 30)
  7. Miscellaneous (Page 38)
  8. Trapping Signals (Page 43)
  9. Understanding Command Translation (Page 50)
  10. Writing Advanced Loops (Page 59)
  11. Creating Remote Shells (Page 67)
  12. More Miscellaneous (Page 73)
  13. Using Quotes (Page 75)





Section 1: Review of a few Basic UNIX Topics

Variables


Page 1



I/O Redirection


Page 2



Backquotes


Page 3



Pipes


Page 4



awk


Page 5







Section 2: Storing Frequently Used Commands in Files: Shell Scripts

Shell Scripts

  • Topics covered: storing commands in a file and executing the file, $USER variable (standard Bourne shell variable)
  • Utilities covered: date, cal, last, pipes

  • Store the following in a file named simple.sh and execute it
    #!/bin/sh
    # Generate some useful info for
    # use at the start of the day
    date
    cal
    last $USER | head -6
    
  • Shows current date, calendar, and a six of your previous logins for security check
  • You might run this at the beginning of each day
  • Notice that the commands themselves are not displayed, only the results
  • To display the commands verbatim as they run, execute with
    sh -v simple.sh
    
  • To echo the commands after variable translation, execute with
    sh -x simple.sh
    
  • With -v or -x (or both) you can easily relate any error message that may appear to the command that generated it
  • When an error occurs in a script, the script continues executing at the next command
  • Verify this by changing 'cal' to 'caal' to force an error, and then run the script again
  • Run the 'caal' script with 'sh -v simple.sh' and 'sh -x simple.sh' and verify the error message comes from cal
  • Now you can re-use commands easily and save some typing and mistakes
  • Other standard variable names include: HOME, PATH, TERM, PAGER, PRINTER

Page 6



Storing Strings in Variables


Page 7



Scripting With sed


Page 8







Section 3: More on Using UNIX Utilities

Performing Arithmetic


Page 9



Translating Characters

  • Topics covered: converting one character to another, translating and saving string stored in a variable
  • Utilities covered: tr

  • Copy the file sdsc.txt to your home directory
  • The utility tr translates characters
    tr 'a' 'Z' < sdsc.txt
    
  • This example shows how to translate the contents of a variable and display the result on the screen with tr
  • Store the following in a file named tr1.sh and execute it
    #!/bin/sh
    # Translate the contents of a variable
    Cat_name="Piewacket"
    echo $Cat_name | tr 'a' 'i'
    
  • This example shows how to change the contents of a variable
  • Store the following in a file named tr2.sh and execute it
    #!/bin/sh
    # Illustrates how to change the contents of a variable with tr
    Cat_name="Piewacket"
    echo "Cat_name is $Cat_name"
    Cat_name=`echo $Cat_name | tr 'a' 'i'`
    echo "Cat_name has changed to $Cat_name"
    
  • You can also specify ranges of characters.
  • This example converts upper case to lower case
    tr 'A-Z' 'a-z' < file
    
  • Now you can change the value of the variable and your script has access to the new value

Page 10







Section 4: Performing Search and Replace in Several Files

Processing Multiple Files


Page 11



Using File Name Wildcards in For Loops


Page 12



Search and Replace in Multiple Files


Page 13







Section 5: Using Command-line Arguments for Flexibility

What's Lacking in the Scripts Above?


Page 14



What are Command-line Arguments?


Page 15



Accessing Command-line Arguments


Page 16



Looping Over the Command-line Arguments


Page 17



If Blocks


Page 18



The read Command


Page 19



Command Exit Status


Page 20



Regular Expressions


Page 21



Greed and Eagerness


Page 22



Regular Expressions Versus Wildcards


Page 23



Getting Clever With Regular Expressions


Page 24



The case Statement


Page 25



The while Statement


Page 26



Example With a while Loop

  • Topics covered: Using a while loop to read and process a file
  • Utilities covered: no new utilities

  • Copy the file while2.data to your home directory
  • The example below uses a while loop to read an entire file
  • The while loop exits when the read command returns false exit status (end of file)
  • Store the following in a file named while2.sh and execute it
    #!/bin/sh
    # Illustrates use of a while loop to read a file
    cat while2.data |   \
    while read line
    do
    	echo "Found line: $line"
    done
    
    
  • The entire while loop reads its stdin from the pipe
  • Each read command reads another line from the file coming from cat
  • The entire while loop runs in a subshell because of the pipe
  • Variable values set inside while loop not available after while loop

Page 27



Interpreting Options With getopts Command


Page 28



Example With getopts

  • Topics covered: interpreting options in a script
  • Utilities covered: getopts

  • The second example shows how to use if blocks to take action for each option
  • Store the following in a file named getopts2.sh and execute it
    #!/bin/sh
    #
    # Usage:
    #
    #	getopts2.sh [-P string] [-h] [file1 file2 ...]
    #
    # Example runs:
    #
    #	getopts2.sh -h -Pxerox file1 file2
    #	getopts2.sh -hPxerox file1 file2
    #
    # Will print out the options and file names given
    #
    
    # Initialize our variables so we don't inherit values
    # from the environment
    opt_P=''
    opt_h=''
    
    # Parse the command-line options
    while getopts 'P:h' option
    do
    	case "$option" in
    	"P")	opt_P="$OPTARG"
    		;;
    	"h")	opt_h="1"
    		;;
    	?)	echo "getopts2.sh: Bad option specified...quitting"
    		exit 1
    		;;
    	esac
    done
    
    shift `expr $OPTIND - 1`
    
    if [ "$opt_P" != "" ]
    then
    	echo "Option P used with argument '$opt_P'"
    fi
    
    if [ "$opt_h" != "" ]
    then
    	echo "Option h used"
    fi
    
    if [ "$*" != "" ]
    then
    	echo "Remaining command-line:"
    	for arg in "$@"
    	do
    		echo "	$arg"
    	done
    fi
    
    
  • Execute it several times with
    sh getopts2.sh -h -Pjunky
    sh getopts2.sh -hPjunky
    sh getopts2.sh -h -Pjunky /etc /tmp
    
  • Can also implement actions inside case statement if desired

Page 29







Section 6: Using Functions

Functions


Page 30



Define a Function


Page 31



Function Arguments


Page 32



Example With Functions


Page 33



Functions in Pipes


Page 34



Inherited Variables


Page 35



Functions -vs- Scripts


Page 36



Libraries of Functions


Page 37







Section 7: Miscellaneous

Here Files


Page 38



Example With Here File


Page 39



Set: Shell Options


Page 40



Set: Split a Line


Page 41



Example With Set


Page 42







Section 8: Trapping Signals

What are Signals?


Page 43



Common Signals


Page 44



Send a Signal


Page 45



Trap Signals


Page 46



Where to Find List of Signals


Page 47



User Signals


Page 48



Experiment With Signals


Page 49







Section 9: Understanding Command Translation

Command Translation


Page 50



Experiment With Translation


Page 51



Order of Translations


Page 52



Order of Translations (continued)


Page 53



Exceptional Case


Page 54



Examples With Translation


Page 55



Examples (continued)


Page 56



Examples (continued)


Page 57



Eval Command


Page 58







Section 10: Writing Advanced Loops

While loops


Page 59



Until loops


Page 60



Redirection of Loops


Page 61



Continue Command


Page 62



Break Command


Page 63



Case Command


Page 64



Example With Case


Page 65



Infinite Loops


Page 66







Section 11: Forking Remote Shells

Remote Shells


Page 67



Examples With rsh


Page 68



Access Control with .Rhosts


Page 69



Remote Shell I/O


Page 70



Return Status


Page 71



Remote Return Status


Page 72







Section 12: More Miscellaneous

Temporary Files


Page 73



Wait Command


Page 74







Section 13: Using Quotes

Quotes


Page 75



Metacharacters


Page 76



Examples With Quotes


Page 77



More Examples With Quotes


Page 78



Searching for Metacharacters


Page 79

Last modified: Wed 15 Aug 2007 11:17:36 AM EDT

Last modified: Tue 10 Dec 2002 06:48:21 AM EST