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