继吉 发表于 2018-8-23 13:34:24

Shell处理用户输入参数----getopts

  特殊变量提醒:
  $# 记录命令行参数个数
  $* 保存所有参数,并当做单个单词保存
  $@ 保存所有参数,当做同一个字符串中的多个独立的单词
  getopts 命令格式:
  getopts optstring variable
  有效字母都会列在optstring中,当前参数保存在 variable中
  示例:
  

  

  
#!/bin/bash
  
whilegetopts:ab:copt
  
do
  
case"$opt" in
  
a)
  
echo"Found the -a option";;
  
b)
  
echo"Found the -b option,wiht value$OPTARG";;
  
c)
  
echo"FOund the -c option";;
  
*)
  
echo"Unknown option :$opt";;
  
esac
  
done
  

  测试
  

  
# sh test.sh-a -b test -c
  
Found the -a option
  
Found the -b option,wiht valuetest
  
FOund the -c option
  

  
# sh test.sh-d
  
Unknown option :?
  

  

  选项字母要求有参数值的时候,在其后加一个冒号;
  去掉错误消息的话,在optstring之前加一个冒号;
  $OPTARG会保存参数值


页: [1]
查看完整版本: Shell处理用户输入参数----getopts