问题
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