shell 传递选项和参数之 getopt 的用法

来源:互联网 发布:数据分析师考试报名 编辑:程序博客网 时间:2024/06/13 10:21

#这是我管理编译的一个脚本,主要部分请看 ===================== 之后的部分

#!/bin/bash


make_clean()
{

}

move_bin()
{

}

make_decoder()
{

}

make_arch()
{

}

make_decoder_image()
{

}

build_help()
{
    echo "no option chosice"
    echo " -a --make arch"
    echo " -c --make clean"
    echo " -d --make decoder"
    echo " -i --make decoder.image"
    echo " -m --cp decoder_main.bin to nfsroot"
    echo " -w --make fb_welcome.bin "
    echo " -h --display this help"
    echo "make decoder"
}

build_welcom()
{
   

}

GETOPTOUT=`getopt acdhimwe:fo "$@"`
SETOUT=`set -- "$GETOPTOUT"`

echo "======="
echo "optout is $GETOPTOUT"            #这个变量没有用,只是为查看getopt 命令的输出
echo "setout is $SETOUT"                    #只为查看set -- 命令的输出
echo "after set $@ " 


#================================================
if [ $# == 0 ]; then
    build_help
fi

set -- `getopt acdhimwe:fo "$@"`                              #set -- 重新组织$1 等参数
while  [ -n "$1" ]
do
    echo "\$1 is $1"
    case $1 in
        -a)
            make_arch
            ;;
        -c)
            make_clean
            ;;
        -d)
            make_decoder
            ;;
        -h)
            build_help
            ;;
        -i)
            make_decoder_image
            ;;
        -m)
            move_bin
            ;;
        -w)
            build_welcom
            ;;
        --)
            shift
            break
            ;;
        -o)
            echo "find -o option"
            ;;
        -f)
            echo "find -f option"
            ;;
        -e)
            echo "find -e option with param $2"
            shift
            ;;
        *)
            echo $1
            echo "unknow option"
    esac
    shift
done

count=1
for param in "$@"
do
    echo "Paraneter \$$count:$param"
    count=$[ $count + 1 ]

done


#=======================

要点:

1. getopt 用法

语法:getopt [options] [--] optstring parameters

例如:getopt ab:cd -a -b he free cat
输出:-a -b he -- free cat
            getopt 根据 ab:cd 将选项和参数 -a -b he free cat  解析为如下格式:
            -a -b he -- free cat
             其中 -- 将选项与非选项参数分开 free 和 cat 就时非选项参数

2. set --

-- Do not change any of the flags; useful in setting $1 to -.

set --  主要是影响特殊变量$1 $2 等,其实在上面的脚本中就是将$1 $2 等参数变量重新组合

例如:

set -- a b c

shell中的特殊位置变量$1 为a $2 为 b $3 为 c

3.如上脚本为build.sh 用法如下:

./build.sh -a -c -d -e dog

./build.sh -acde  dog

上面两个命令执行结果相同。