【问题标题】:I have a script and I want it to tell me how many paramters it has我有一个脚本,我希望它告诉我它有多少参数
【发布时间】:2014-05-16 04:55:36
【问题描述】:
我需要它来告诉我程序中有多少参数,但它没有按我想要的方式工作
if [ "$#" -ne 1 ];
then
echo "Illegal number of parameters is"
me=`basename $0`
echo "File Name: $0"
echo "First Parameter : $1"
fi
【问题讨论】:
标签:
bash
parameters
parameter-passing
【解决方案1】:
当您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
【解决方案2】:
$# 包含您想要的所有内容,无论是传递给脚本的参数还是传递给函数的位置参数的数量。
#!/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'