shell学习笔记2013-11-12

#!/bin/bash -
shell 学习指南8.1 修改版
# pathfind  [--all] [--?] [--help] [--version] envvar pattern



IFS=" 
    "

OLDPATH="$PATH"
PATH=/bin:/usr/bin
export PATH


error()
{
    echo "$@" 1>&2
    usage_and_exit 1
}

usage()
{
    echo "Usage:$PROGRAM [--all] [--?] [--help] [--version] [--quiet] [--test x|r|h] [--trace] envvar pattern(s)"
}
usage_and_exit()
{
    usage
    exit $1
}

version()
{
    echo "$PROGRAM version $VERSION"
}
warning()
{
    echo "$@" 1>&2
    EXITCODE=`expr $EXITCODE + 1`
}


all=no
envvar=
EXITCODE=0
PROGRAM=`basename $0`
VERSION=1.0
TRACE=no
TEST_OPTION=f

while [[ $# -gt 0 ]]
do
    case $1 in
    -a|--a|--all|-all|-al|--al)
        all=yes
        ;;
    --help|-help|-h|--h)
        usage_and_exit 0
        ;;
    --v|--V|--version|-v|-V|-version)
        version
        exit 0
        ;;
    --quiet|-quiet |-q | --q)
        exec 2>/dev/null
        exec 1>/dev/null
        ;;
    --trace|-trace )
        TRACE=yes
        ;;
    --test | -test )
        shift
        TEST_OPTION=$1
        if [ "X$TEST_OPTION" != 'Xr' ] && \
            [ "X$TEST_OPTION" != 'Xx' ] && \
                [ "X$TEST_OPTION" != 'Xh' ]
        then
        error "TEST_OPTION unkown:$1 "
        fi
        ;;
    -*)
        error "Unrecognized option:$1"
        ;;
    *)
        break
        ;;
    esac
    shift
done

envvar="$1"
test $# -gt 0 && shift
test "x$envvar"  =  "xPATH"  && envvar=OLDPATH
dirpath=`eval echo   '${'"$envvar"'}' 2> /dev/null | tr : ' '`


if test -z "$envvar"
then
    error Environment variable missing or empty
elif test "x$dirpath" = "x$envvar"
then
    error "Broken sh on this platform:cannot expand $envvar"
elif test -z "$dirpath"
then
    error Empty directory search path
elif test $# -eq 0
then
    exit 0
fi


for pattern in "$@"
do
    result=
    for dir in $dirpath
    do
        test -d $dir || continue
        for file in $dir/$pattern
        do
           if  test -$TEST_OPTION "$file"
            then
                result="$file"
                if [[ "X$TRACE" = 'Xno' ]]
                then
                    echo $result
                else
                    echo $result >&2
                fi
                test "$all" = "no"  && break 2
            fi
        done
    done
    test -z "$result" && warning "$pattern: no found "
done

test $EXITCODE -gt 125 &&  EXITCODE=125
exit $EXITCODE

你可能感兴趣的:(shell学习笔记2013-11-12)