通過例子理解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是爲了防止選項參數有空格,這樣輸出就會出錯了,可以去掉""測試下
###############################
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章