通过例子理解shell下使用getopts和getopt

脚本都是在网上获取的,只是拿按个人理解讲一下

在写一些特殊脚本中可能要遇到获取可变参数的脚本,为了简化可能需要进行选项支持,下面了解下getopt及getopts在脚本中应该的例子讲解

getopts是为了让脚本支持短选项功能,而getopt长短选项都可以支持

脚本名为getopts.sh

#!/bin/bash

 
echo "$*"
echo ---------------------------------
while getopts ":a:bc:" opt
do
    case $opt in
        "a") echo "a" $opt $OPTIND $OPTARG;;
        "b") echo 'b' $opt $OPTIND $OPTARG;;
        "c") echo 'c' $opt $OPTIND $OPTARG;;
        "?") echo "options error";;
        ":") echo "no value error";;
    esac
done
 
echo $OPTIND
shift $(($OPTIND-1))
echo -------------------------------
echo "$*"
######################################
以下面这样运行得到的结果就对$OPTIND、$OPTARG、?、:这几个选项的了解了。getopts最前的:表示忽略错误输出,可以去掉自己测试下,shift $(($OPTIND-1))表示把传入的第$OPTIND个参数变成$1
sh getopts.sh
sh getopts.sh -d
sh getopts.sh -a
sh getopts.sh -b
sh getopts.sh -a 100
sh getopts.sh -b 100
sh getopts.sh -a100  
sh getopts.sh -a 100 23
 
#######################################
脚本名为getopt.sh
#!/bin/bash
 
 
help()
{
    echo "need help"
}
mess()
{
    local mess=$1
    echo "$mess"
}
ARGV=$( getopt -o hm: --long help,mess: -- "$@" )
eval set -- "$ARGV"
while true
do
    case "$1" in
    -h|--help)
        help
        shift
    ;;
    -m|--mess)
        mess  "$2"
        shift
    ;;
    *)
        break
    ;;
    esac
shift
done
###############################
以下面方式运行下就可以了解了
sh getopt.sh -h
sh getopt.sh --mess="hello world"
sh getopt.sh -m "hello world"
sh getopt.sh -b
sh getopt.sh -- -b
 
ARGV就是命令替换
eval就是获取上面的getopt命令得到的内容
set 设置环境变量
case $1就是set后得到getopt命令的第一个参数.
-m|--mess选项用"$2"面不直接$2是为了防止选项参数有空格,这样输出就会出错了,可以去掉""测试下
###############################

你可能感兴趣的:(shell,getopt,getopts)