【问题标题】:Ambiguous redirect in a Unix Shell Script with if-elif-else statement带有 if-elif-else 语句的 Unix Shell 脚本中的不明确重定向
【发布时间】:2016-02-04 05:25:27
【问题描述】:

我刚刚开始在 Unix 中编写 if-else 语句。这是我最近写的一个简短的 Bash 脚本。我不断收到一个模棱两可的重定向错误,但我无法找出问题所在。

执行时,我收到以下错误消息:

stringComp: line 17: $str2: ambiguous redirect
stringComp: line 20: $str2: ambiguous redirect
stringComp: line 23: [: too many arguments

这是脚本:

str1="I like turtles"
str2="I want to be Iron Man"

if [ $str1 > $str2 ]
then
        echo "The first string is longer than the second"
elif [ $str1 < $str2 ]
then
        echo "The second string is longer than the first"
elif [ $str1 = $str2 ]
then
        echo "Both strings are of equal length"
else
        echo "Invalid argument"
fi

有什么建议可以在这里做什么吗?谢谢。

【问题讨论】:

    标签: bash shell unix if-statement logic


    【解决方案1】:

    $str1 &gt; $str2 不比较字符串长度,&gt;[ 一起使用时实际上是重定向运算符,[ 在 Unix 系统中是一个单独的程序。

    您可以使用${#str1} 来获取字符串长度:

    str1="I like turtles"
    str2="I want to be Iron Man"
    
    if [[ ${#str1} -gt ${#str2} ]]
    then
            echo "The first string is longer than the second"
    elif [[ ${#str1} -lt ${#str2} ]]
    then
            echo "The second string is longer than the first"
    elif [[ ${#str1} -eq ${#str2} ]]
    then
            echo "Both strings are of equal length"
    else
            echo "Invalid argument"
    fi
    

    在 bash 中使用 [[...]] 也更好。

    【讨论】:

    • 也可以使用-gt,-lt,-eq等
    • @sudheeshshetty 实际上,您必须使用-gt-lt,否则它会进行字符串比较而不是数字比较。不同之处在于,例如[[ 10 &gt; 9 ]] 为假,因为“1”在排序顺序中排在“9”之前;但[[ 10 -gt 9 ]] 是真的。或者你可以使用像(( 10 &gt; 9 ))这样的数字表达式。
    • 那么这里我们可能不得不使用-gt、-lt和-eq。
    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多