linux - shellscript - “$#” [duplicate]

眉间皱痕 提交于 2021-02-10 22:27:37

问题


I have a shellscript with the following lines:

set -o nounset
set -o errexit
set -o xtrace

if [ "$#" -ne 0 ]
then
   echo 'A message'
   exit 1
fi

Can somebody explain the commands, in particular the setter and the "$#" portion?


回答1:


$# is the number of arguments passed to the script.

So this

if [ "$#" -ne 0 ]

check ensures that if no arguments are passed then the script exits, which implies that the script expects one or more arguments.


In a simple script called my_script, have this:

#!/bin/bash

echo $#

and run with:

$ ./my_script # prints 0
$ ./my_script a b cde  # prints 3
$ ./my_script 1 2 3 4 # prints 4

The set built-in options:

set -o unset (equivalent to set -u): Treats unset variable as error.

set -o errexit (equivalent to set -e): Exits immediately on error.

set -o xtrace (equivalent to set -x): Displays the expanded command. Typically used to to debug shell scripts.

Consider a simple script called opt to demonstrate this:

#!/bin/bash
set -e
set -u
set -x

cmd="ps $$"
${cmd}

echo $var # 'var' is unset. So it's an "error". Since we have
          # 'set -o e', the script exits.
echo "won't print this

"

outputs something like:

+ cmd='ps 2885'
+ ps 2885
  PID TTY      STAT   TIME COMMAND
 2885 pts/1    S+     0:00 /bin/bash ./s
./s: line 9: var: unbound variable

The first two lines in the output (starting with +) are due to set -x.
The next two are the result of running the ${cmd}.
The next line is the error, happened as the result of set -u.

You can read more about the set built-in options here.




回答2:


In Bash, $# keeps the number of command line arguments. In your case, the conditional part will fire only when there are some.

I believe very similar question was answered here, second or third answer matching your problem.



来源:https://stackoverflow.com/questions/34370525/linux-shellscript

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