【问题标题】:shell functions and argument passing issue [duplicate]shell函数和参数传递问题[重复]
【发布时间】:2016-03-27 23:51:42
【问题描述】:

我需要将参数传递给 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

【问题讨论】:

  • 您可能想要使用case 语句,而不是大量的级联ifs。
  • 顺便说一句,不仅仅是测试需要引号来确保内容在没有修改的情况下通过;你还想要func1 "$2"func2 "$2"

标签: linux bash function shell arguments


【解决方案1】:

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

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

【讨论】:

  • 可能还提到需要空格(在第二次调用中缺少)。
  • 感谢您的快速帮助。我是 STCK OVFL 和 linux shell 的新手。另外,我认为回复会帮助像我这样搜索回复而不是问题列表的新手?
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 2022-01-26
  • 2015-12-13
  • 1970-01-01
  • 2017-07-05
  • 2019-11-21
  • 1970-01-01
相关资源
最近更新 更多