我有以下bash脚本,我有点混淆什么是$ opt含义。我在搜索后没有找到有关它的详细信息。
test.sh:
echo "opt:" $opt
for opt; do
echo $opt
done
输出:
./test.sh -a -b c
opt:
-a
-b
c
答案 0 :(得分:3)
for
语句通常如下:
for x in a b c; do
...
done
$x
在第一次迭代时的值为a
,然后是b
,然后是c
。
a b c
部分不需要按字面意思写出,迭代的列表可以由变量给出,如$@
,其中包含当前范围的所有参数列表:
for x in "$@"; do
...
done
此外,如果您未明确提供任何列表,则in "$@"
假定为:
for x; do
...
done
答案 1 :(得分:2)
for name [ [ in [ word ... ] ] ; ] do list ; done The list of words following in is expanded, generating a list of items. The variable name is set to each element of this list in turn, and list is executed each time. If the in word is omit‐ ted, the for command executes list once for each positional parameter that is set (see PARAMETERS below). The return status is the exit status of the last command that executes. If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0.
因此,如果缺少in
字,则for循环遍历脚本的位置参数,即$1
,$2
,$3
,....
名称opt
没有什么特别之处,可以使用任何合法的变量名称。考虑这个脚本及其输出:
#test.sh
echo $* # output all positional parameters $1, $2,...
for x
do
echo $x
done
$ ./test.sh -a -b hello
-a -b hello
-a
-b
hello
答案 2 :(得分:1)
$opt
不是内置或特殊变量。如果在脚本中提及(for opt
之外没有in something
部分,@mhawke already explained),则应在脚本中先前定义它,或者预期它是export
ed在运行脚本之前。