shell函数和参数传递问题

时间:2015-12-21 20:11:18

标签: linux bash function shell arguments

我需要将参数传递给shell脚本,在验证之后,需要将其作为相同或修改后的脚本中的函数传递给它。

#!/bin/sh
func1(){
echo "called func1 with $1" ;
exit 0 ;
}

func2(){
echo "called func2 with $1" ;
exit 0 ;
}

if [ $# -eq 0 ]
then
    echo "Usage:" ;
    echo "script.sh arg1 arg2" ;
    exit -1 ;
fi

if [ "$1" -eq "txt1" ]
then
    func1 $2 ;
    exit 0 ;
fi

if ["$1" -eq "txt2" ]
then
    func2 $2 ;
    exit 0;
fi

我得到的回应是

sh script.sh txt1
sh: txt1: bad number
sh: txt1: bad number

1 个答案:

答案 0 :(得分:1)

您使用错误的运算符进行字符串比较。您想使用=,而不是-eq(比较整数)。

请注意,[只是shell的内部命令,因此您需要将空格与其参数分开。 (在脚本的第三次测试中。)