BASH 脚本和参数 with/out 选项
BASH script and parameters with/out options
我想创建具有两种类型的脚本 arguments/options。
例如:
./script.sh --date 15.05.05 --host localhost
但我也希望能够 运行 使用没有值的参数:
./script --date 15.0.50.5 --host localhost --logs --config
现在我有这样的东西:
while [[ $# -gt 0 ]]; do
case in
--date|-d ) DATE="" ;;
--host|-h ) HOST="" ;;
--logs ) LOGS=true ;;
--config ) CONFIG=true ;;
# --all ) LOGS=true ; PROCS=true ; CONFIG=true ;;
* ) usage; exit 1 ;;
esac
shift 2
done
但是,当我这样使用它时,我必须在 --logs
和 --config
之后放置一个值,以防止 shift
获取下一个有效参数,例如这个:
./script.sh --date 15.05.05 --logs 1 --config 1
还有其他方法吗?
这个简单的解决方案怎么样?
while [[ $# -gt 0 ]]; do
case in
--date|-d ) DATE="" ; shift 2 ;;
--host|-h ) HOST="" ; shift 2 ;;
--logs ) LOGS=true ; shift 1 ;;
--config ) CONFIG=true ; shift 1 ;;
* ) usage; exit 1 ;;
esac
done
或者你可以使用getopts(虽然它只支持短参数),大约是这样的:
while getopts ":d:h:lc" OPT; do
case $opt in
-d ) DATE="$OPTARG" ;;
-h ) HOST="$OPTARG" ;;
-l ) LOGS=true ;;
-c ) CONFIG=true ;;
* ) usage; exit 1 ;;
esac
done
我想创建具有两种类型的脚本 arguments/options。
例如:
./script.sh --date 15.05.05 --host localhost
但我也希望能够 运行 使用没有值的参数:
./script --date 15.0.50.5 --host localhost --logs --config
现在我有这样的东西:
while [[ $# -gt 0 ]]; do
case in
--date|-d ) DATE="" ;;
--host|-h ) HOST="" ;;
--logs ) LOGS=true ;;
--config ) CONFIG=true ;;
# --all ) LOGS=true ; PROCS=true ; CONFIG=true ;;
* ) usage; exit 1 ;;
esac
shift 2
done
但是,当我这样使用它时,我必须在 --logs
和 --config
之后放置一个值,以防止 shift
获取下一个有效参数,例如这个:
./script.sh --date 15.05.05 --logs 1 --config 1
还有其他方法吗?
这个简单的解决方案怎么样?
while [[ $# -gt 0 ]]; do
case in
--date|-d ) DATE="" ; shift 2 ;;
--host|-h ) HOST="" ; shift 2 ;;
--logs ) LOGS=true ; shift 1 ;;
--config ) CONFIG=true ; shift 1 ;;
* ) usage; exit 1 ;;
esac
done
或者你可以使用getopts(虽然它只支持短参数),大约是这样的:
while getopts ":d:h:lc" OPT; do
case $opt in
-d ) DATE="$OPTARG" ;;
-h ) HOST="$OPTARG" ;;
-l ) LOGS=true ;;
-c ) CONFIG=true ;;
* ) usage; exit 1 ;;
esac
done