[英]What is $opt variable for command line parameter in bash
I have below bash script, I am a bit confuse about what is $opt meaning. 我在bash脚本下面,对$ opt的含义有些困惑。 and I do not find detail information about it after search. 搜索后我没有找到有关它的详细信息。
test.sh: test.sh:
echo "opt:" $opt for opt; do echo $opt done
output: 输出:
./test.sh -a -bc opt: -a -bc
the for
statement goes generally like this: for
语句通常如下所示:
for x in a b c; do
...
done
$x
has the value a
on the first iteration, then b
, then c
. $x
在第一次迭代中的值为a
,然后为b
,然后为c
。 the abc
part need not be written out literally, the list to iterate through can be given by a variable, like the $@
, which has the list of all arguments to the current scope: abc
部分不需要abc
写出,要遍历的列表可以由变量给出,例如$@
,其中包含当前作用域的所有参数的列表:
for x in "$@"; do
...
done
further, in "$@"
is assumed if you provide no list explicitly: 此外,如果您未明确提供任何列表,则假定 in "$@"
:
for x; do
...
done
From the bash(1) man page : 在bash(1)手册页中 :
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.
So, if the in
word is missing the for loop iterates over the positional arguments to the script, ie $1
, $2
, $3
, .... 因此,如果in
单词缺失,则for循环遍历脚本的位置参数,即$1
, $2
, $3
,...。
There is nothing special about the name opt
, any legal variable name can be used. 名称opt
没什么特别的,可以使用任何合法变量名称。 Consider this script and its output: 考虑一下此脚本及其输出:
#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
$opt
is not a built-in or special variable. $opt
不是内置变量或特殊变量。 If it's mentioned in the script (outside of for opt
without the in something
part, which @mhawke already explained ) it should either be defined earlier in the script or it's expected that it is export
ed before running the script. 如果它在脚本中提到的(外for opt
没有in something
的一部分,这@mhawke已经说明 )它应该要么早在脚本中定义或它的预期,这是export
版运行脚本之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.