1

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

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Aviel Ovadiya
  • 69
  • 1
  • 2
  • 10
  • 2
    This issue will be automatically detected by http://shellcheck.net/; consider making a habit of running code through there before asking questions here. – Charles Duffy Jan 20 '18 at 00:20
  • 1
    BTW, when trying to write a question title, try to describe the specific problem as much as possible -- ie. not just "issue with X", but "Why is X doing Y when Z is expected?". I've attempted to edit towards that end here; that way folks can see at a glance if they have the same problem (if the question is answered), or if they're likely to be able to help (if not). – Charles Duffy Jan 20 '18 at 00:23

1 Answers1

3

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
John1024
  • 109,961
  • 14
  • 137
  • 171