我有一个脚本,我希望它告诉我它有多少参数



我需要它告诉我程序中有多少参数,但它没有按照我想要的方式工作

if [ "$#" -ne 1 ]; 
then
  echo "Illegal number of parameters is"
  me=`basename $0`
  echo "File Name: $0"
  echo "First Parameter : $1"
fi

当您echo $#变量时,它会为您提供传递给脚本的参数数

script.sh 的内容

#!/bin/bash
echo "Number of parameters passed are $#"

$ chmod u+x script.sh
$ ./script.sh apple 1 2 ball 3
Number of parameters passed are 4

$#包含您想要的所有内容,无论是传递给脚本的参数还是传递给函数的位置参数的数量。

  #!/bin/bash
    myfunc(){
      echo "The number of positional parameter : $#"
      echo "All parameters or arguments passed to the function: '$@'"
      echo
    }

    printf "No of parameters passed:$#n" 
    myfunc test123
    myfunc 1 2 3 4 5
    myfunc "this" "is" "a" "test"

喜欢

$ ./sample.sh 1 2 3 4 5
No of parametere passed:5
The number of positional parameter : 1
All parameters or arguments passed to the function: 'test123'
The number of positional parameter : 5
All parameters or arguments passed to the function: '1 2 3 4 5'
The number of positional parameter : 4
All parameters or arguments passed to the function: 'this is a test'

最新更新