![](/img/trans.png)
[英]Shell Script using if/then/elif/then/else Construct Not working
[英]Ambiguous redirect in a Unix Shell Script with if-elif-else statement
我刚刚开始在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
有什么建议在这里做什么? 谢谢。
$str1 > $str2
没有比较字符串长度,当与[
是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中使用[[...]]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.