Why is [ “$foo”==“$bar” ] always true in bash? [duplicate]

爷,独闯天下 提交于 2019-12-31 04:07:25

问题


I tried to compare user input between to string Here is my code

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

Its always go to the Encode statement, Why?. And how to fix it


回答1:


In bash, spaces count. Replace:

if [ "$Encode"=="$EncOrDec" ]; then

With:

if [ "$Encode" = "$EncOrDec" ]; then

Without spaces, bash is just testing whether the string "$Encode"=="$EncOrDec" is empty or not. Since it is never empty, the then clause is always executed.

Also, as a minor detail, when using [...], the use of = for string equality is POSIX standard. Bash accepts == but == is not standard and won't be reliably portable.

The same applies to the elif line. Replace:

elif [ "$Decode"=="$EncOrDec" ]; then

With:

elif [ "$Decode" = "$EncOrDec" ]; then


来源:https://stackoverflow.com/questions/48351269/why-is-foo-bar-always-true-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!