代碼如下: #!/bin/bash if [ $# -lt 1 ]; then echo "error.. need args" exit 1 fi echo "commond is $0" echo "args are:" for arg in "$@" do echo $arg done
運行命令:
代碼如下: ./getargs.sh 11 22 cc commond is ./getargs.sh args are: 11 22 cc 2,getopts (shell內(nèi)置命令) 處理命令行參數(shù)是一個相似而又復(fù)雜的事情,為此,c提供了getopt/getopt_long等函數(shù),c++的boost提供了options庫,在shell中,處理此事的是getopts和getopt。 getopts/getopt的區(qū)別,getopt是個外部binary文件,而getopts是shell builtin。
代碼如下: [root@jbxue ~]$ type getopt getopt is /usr/bin/getopt [root@jbxue ~]$ type getopts getopts is a shell builtin getopts不能直接處理長的選項(如:--prefix=/home等) 關(guān)于getopts的使用方法,可以man bash 搜索getopts getopts有兩個參數(shù),第一個參數(shù)是一個字符串,包括字符和“:”,每一個字符都是一個有效的選項,如果字符后面帶有“:”,表示這個字符有自己的參數(shù)。getopts從命令中獲取這些參數(shù),并且刪去了“-”,并將其賦值在第二個參數(shù)中,如果帶有自己參數(shù),這個參數(shù)賦值在“optarg”中。提供getopts的shell內(nèi)置了optarg這個變變,getopts修改了這個變量。 這里變量$optarg存儲相應(yīng)選項的參數(shù),而$optind總是存儲原始$*中下一個要處理的元素位置。