bash - 参数解析(getopts)

getopts用于解析命令行参数,是“shell builtin commands are inherited from the Bourne Shell”


参考:

http://www.gnu.org/s/bash/manual/html_node/Bourne-Shell-Builtins.html#Bourne-Shell-Builtins


代码:

#!/bin/bash
# Example: args parse



usage() {
    local prog="`basename $1`"
    echo "Usage: $prog -n name1 [name2...] [-c count] [-D DestDir]"
    echo "       $prog -h for help."
    exit 1
}

showhelp() {
    echo "Usage: `basename $1`: -n name1 [name2...] [-c count] [-D OutputDir]" 
    echo "  -n target name (\"None\" for no tag)"
    echo "  -c count for each name (\"None\"=1)"
    echo "  -D output directory"
    echo "  -h show this help"
    exit 1
}


name=
count=
outputdir=
file="${!#}"
filename="`basename $file`"
run=false		# once for "None"


while getopts "n:c:D:h" arg
do
    case $arg in
        n)  name=$OPTARG;;
        c)  count=$OPTARG;;
        D)  outputdir=$OPTARG;;
        h)  showhelp $0;;
        ?)  usage $0;;
    esac
done


#[ ! -f $file ] && usage $0 
[ -z "$name" ] && usage $0
[ -z "$count" ] && count=1
[ -z "$outputdir" ] && outputdir="`dirname $file`"


for n in $name
do
    for((c=0; c<count; c++))
    do
        if [ "None" == "$n" ];then
            if [ "false" == "$run" ];then
                run=true
                c=""
            else
                break
            fi
        fi
        suffix="${n}${c}"
        echo $filename | sed "s/.iso$/-${suffix}.iso/"
    done
done

exit 0






你可能感兴趣的:(c,shell,File,bash,each,output)