为什么 [ "$foo"=="$bar" ] 在 bash 中总是 true?
Why is [ "$foo"=="$bar" ] always true in bash?
我尝试将用户输入与字符串进行比较
这是我的代码
Encode="Encode"
Decode="Decode"
printf "Enter name of file: "
read fileName
printf "Encode Or Decode: "
read EncOrDec
if [ "$Encode"=="$EncOrDec" ]; then
printf "Encode Nice\n"
elif [ "$Decode"=="$EncOrDec" ]; then
printf "Decode Nice\n"
else
printf "Nothing\n"
fi
它总是转到 Encode 语句,为什么?。
以及如何修复它
在 bash 中,空格很重要。替换:
if [ "$Encode"=="$EncOrDec" ]; then
与:
if [ "$Encode" = "$EncOrDec" ]; then
没有空格,bash只是测试字符串"$Encode"=="$EncOrDec"
是否为空。因为它 never 为空,所以总是执行 then
子句。
此外,作为一个次要细节,当使用 [...]
时,使用 =
进行字符串相等是 POSIX 标准。 Bash 接受 ==
但 ==
不是标准的,不能可靠地移植。
elif
行也是如此。替换:
elif [ "$Decode"=="$EncOrDec" ]; then
与:
elif [ "$Decode" = "$EncOrDec" ]; then
我尝试将用户输入与字符串进行比较 这是我的代码
Encode="Encode"
Decode="Decode"
printf "Enter name of file: "
read fileName
printf "Encode Or Decode: "
read EncOrDec
if [ "$Encode"=="$EncOrDec" ]; then
printf "Encode Nice\n"
elif [ "$Decode"=="$EncOrDec" ]; then
printf "Decode Nice\n"
else
printf "Nothing\n"
fi
它总是转到 Encode 语句,为什么?。 以及如何修复它
在 bash 中,空格很重要。替换:
if [ "$Encode"=="$EncOrDec" ]; then
与:
if [ "$Encode" = "$EncOrDec" ]; then
没有空格,bash只是测试字符串"$Encode"=="$EncOrDec"
是否为空。因为它 never 为空,所以总是执行 then
子句。
此外,作为一个次要细节,当使用 [...]
时,使用 =
进行字符串相等是 POSIX 标准。 Bash 接受 ==
但 ==
不是标准的,不能可靠地移植。
elif
行也是如此。替换:
elif [ "$Decode"=="$EncOrDec" ]; then
与:
elif [ "$Decode" = "$EncOrDec" ]; then