【发布时间】:2020-01-26 06:06:13
【问题描述】:
考虑下面的代码来解析 bash 脚本参数(比如说example.sh):
#!/bin/bash
positional=()
while [ $# -gt 0 ]
do
arg="$1"
case ${arg} in
-h|--help|\?) show_usage; exit 0 ;;
-v|--verbose) verbose=1; shift ;;
-f|--file) theFile="$2"; shift; shift;;
*) positional+=("$1"); shift ;;
esac
done
set -- "${positional[@]}"
arg1a="${positional[0]}"; arg1b="$1" # same result, $arg1a == $arg1b
arg2a="${positional[1]}"; arg2b="$2" # same result, $arg2a == $arg2b
通过以下脚本调用:
./example.sh pos1 -v -f toto.txt pos2
- 在循环之前,
"$1" == "pos1"和"$5" == "pos2" - 循环之后,
set --、$1、$2和$5之前未定义 - 在
set --、"$1" == "pos1"和"$2" == "pos2"之后
而且,在set --、${positional[0]} == "pos1"和${positional[1]} == "pos2"之后。
那么,问题是:使用set -- "${positional[@]}" 的实际意义是什么?
我们确实可以按照提供的顺序获取位置参数的值(使用${positional[i]}),而无需将其恢复为$1 和$2。因此,我不明白使用set -- 的意义。如果我们不在这里使用它,那么$# -eq 0 就是这样......
请提供一个现实生活中的示例,其中set -- 是强制使用的,即使使用此${positional[]} 数组也是如此。
【问题讨论】: