什么是bash中命令行参数的$ opt变量

时间:2015-02-28 09:06:37

标签: bash command-line

我有以下bash脚本,我有点混淆什么是$ opt含义。我在搜索后没有找到有关它的详细信息。

test.sh:

echo "opt:" $opt for opt; do echo $opt done

输出:
./test.sh -a -b c opt: -a -b c

3 个答案:

答案 0 :(得分:3)

for语句通常如下:

for x in a b c; do
  ...
done

$x在第一次迭代时的值为a,然后是b,然后是ca b c部分不需要按字面意思写出,迭代的列表可以由变量给出,如$@,其中包含当前范围的所有参数列表:

for x in "$@"; do
  ...
done

此外,如果您未明确提供任何列表,则in "$@" 假定为

for x; do
  ...
done

答案 1 :(得分:2)

来自bash(1) man page

   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),则应在脚本中先前定义它,或者预期它是exported在运行脚本之前。