shell脚本选项参数处理学习getopts|getopt

时间:2021-12-01 15:47:49

       在bash中,可以用以下三种方式来处理命令行参数,每种方式都有自己的应用场景。

  • 手工处理方式
  • getopts
  • getopt

(1)手动处理方式

#!/bin/bash 
for arg in "$@"
do
echo $arg
done

(2)getopts

#!/bin/bash

while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数
do
case $arg in
a)
echo "a's arg:$OPTARG" #参数存在$OPTARG中
;;
b)
echo "b"
;;
c)
echo "c"
;;
?) #当有不认识的选项的时候arg为?
echo "unkonw argument"
exit 1
;;
esac
done
上面test.sh脚本就可以./test.sh -a arg -bc来执行了

(3)getopt

未完待续》》》