为什么["$ foo" =="$ bar" ]在bash中始终是正确的? [英] Why is [ "$foo"=="$bar" ] always true in bash?
问题描述
我试图将用户输入与字符串进行比较 这是我的代码
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
它总是转到Encode语句,为什么? 以及解决方法
Its always go to the Encode statement, Why?. And how to fix it
推荐答案
在bash中,空格是计数.替换:
In bash, spaces count. Replace:
if [ "$Encode"=="$EncOrDec" ]; then
使用:
if [ "$Encode" = "$EncOrDec" ]; then
没有空格,bash只是测试字符串"$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.
此外,作为次要细节,使用[...]
时,使用=
进行字符串相等是POSIX标准. Bash接受==
,但是==
不是标准的,并且不会可靠地移植.
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.
elif
行也是如此.替换:
elif [ "$Decode"=="$EncOrDec" ]; then
使用:
elif [ "$Decode" = "$EncOrDec" ]; then
这篇关于为什么["$ foo" =="$ bar" ]在bash中始终是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!