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

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

#!/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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值