What is $opt variable for command line parameter in bash

别说谁变了你拦得住时间么 提交于 2020-01-21 12:16:27

问题


I have below bash script, I am a bit confuse about what is $opt meaning. and I do not find detail information about it after search.

test.sh:

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

output:
./test.sh -a -b c opt: -a -b c


回答1:


From the 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.

So, if the in word is missing the for loop iterates over the positional arguments to the script, i.e. $1, $2, $3, ....

There is nothing special about the name opt, any legal variable name can be used. 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



回答2:


the for statement goes generally like this:

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

$x has the value a on the first iteration, then b, then c. the a b c 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:

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

further, in "$@" is assumed if you provide no list explicitly:

for x; do
  ...
done



回答3:


$opt is not a built-in or special variable. 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 exported before running the script.



来源:https://stackoverflow.com/questions/28779993/what-is-opt-variable-for-command-line-parameter-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!