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