shell getopts用法

eg:sh test.sh -u tom -p 123456;

getopts的使用形式:getopts OPTION_STRING VAR;

OPTION_STRING:-u,-p这种自定义选项;

脚本中$OPTARG,就是tom、123456自定义选项后的参数

参数后应接冒号“:”;

测试代码:

#!/bin/bash
#
while getopts "u:p:" opt; do
  case $opt in
    u)
        use=$OPTARG
        echo "user is $use" ;;
    p)
        passwd=$OPTARG
        echo "passwd is $passwd" ;;
    \?)
        echo "invalid arg" ;;
  esac
done

运行结果:

# sh test.sh -u tom -p 123456
user is tom
passwd is 123456
posted @ 2018-02-28 11:23  houyongchong  阅读(2408)  评论(0编辑  收藏  举报