今天,我必须检查输入参数的存在和数量。我有以下脚本:
#!/bin/bash
echo "*** Test ***"
echo
echo $#
echo $*
function test1(){
echo "test"
}
function GetTime()
{
echo "Get Time function"
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
else
test1
fi
}
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
else
test1
GetTime
fi
当我输入./test.sh GetTime时,我得到
*** Test ***
1
GetTime
test
Get Time function
Illegal number of parameters
我不明白为什么第一个条件与GetTime()函数中包含的条件之间的行为不同。有人可以帮助我吗?
预先感谢
这是不同的,因为$#
首先要if
引用shell脚本的参数数量。其中,$#
以秒为单位表示GetTime
函数的自变量数
为了了解更多,我将GetTime
功能修改为
#!/bin/bash
echo "*** Test ***"
echo
echo $#
echo $*
function test1(){
echo "test"
}
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
else
test1
fi
function GetTime()
{
echo "Get Time function"
echo "$# $@"
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
else
test1
fi
}
GetTime
GetTime 2
给输出为
*** Test ***
1
GetTime
test
Get Time function
0
Illegal number of parameters
Get Time function
1 2
test
这里的第一个电话GetTime
给
Get Time function
0
Illegal number of parameters
0
传递的参数数量在哪里
和第二次呼叫为 GetTime 2
生产的产出
Get Time function
1 2
test
1
传递的参数数量在哪里2
,参数本身在哪里
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句