Example Shell Scripts

Team-Fly    

Solaris™ Operating Environment Boot Camp
By David Rhodes, Dominic Butler
Table of Contents
Chapter 5.  Shells


This script does the same thing as the which command. It will search the user's PATH for the first occurrence of the command supplied as a parameter:

 #!/bin/ksh if [[ -z ${1} ]] then   echo "usage: ${0} command" >&2   exit 1 else   cmd=${1} fi dirs=$(echo ${PATH} | sed 's/^:/. /                       s/::/ . /                       s/:$/ ./                       s/:/ /g') for dir in ${dirs} do   if [[ -f ${dir}/${cmd} ]]   then     echo ${dir}/${cmd}     exit   fi done echo "no ${cmd} in ${dirs}" 

(Note: Some implementations of which do not display anything if the command supplied is not found. If you want to emulate this behavior, simply remove the final echo statement.)

This second example is a script that will allow you to change permission of a file (or files) using the full text representation of the permissions rather than the octal version. For example, if the script were called chmode (so as not to clash with chmod), it could be used as follows:

 chmode rwxrwxr-x t* 

This will change the permissions of all files in the current directory beginning with the letter "t" to 775 without you needing to work out the 755 bit.

This script was included here as it demonstrates a number of common and useful constructs, namely:

  • Handling wildcards (although the shell does the hard part)

  • Dealing with a variable number of filename parameters

  • The use of command substitution

  • Creating a wrapper around an existing UNIX command

  • Redirecting error messages (in this case, throwing them away)

  • Writing your own error message to standard error

 #!/bin/ksh if [[ ${#} -lt 2 ]] then   echo "usage: ${0} permissions file??"   exit 1 fi perms=${1} shift binPerms=$(echo ${perms} | sed 's/[rwx]/1/g                            s/-/0/g') octPerms=$(echo "obase=8\nibase=2\n${binPerms}" | bc) for i in ${*} do   chmod ${octPerms} ${i} 2>/dev/null   if [[ ${?} -ne 0 ]]   then     echo "${0}: could not change permissions of ${i}" >&2   fi done 

(Note: This script does not handle special cases of permissions such as the setuid or setgid bits. You may wish to incorporate these into this script.)


    Team-Fly    
    Top
     



    Solaris Operating Environment Boot Camp
    Solaris Operating Environment Boot Camp
    ISBN: 0130342874
    EAN: 2147483647
    Year: 2002
    Pages: 301

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net