1

i'm new to shell script. i wrote a test script that encode/decode plain text to base64 string. but it does not work what i thought. i want to decode base64 encoded string to plain text if ENCODING var is false.

my script:

#!/bin/bash

ENCODING=false
INPUT_STRING=dGVzdF9zdHJpbmcK

if [ $ENCODING ]; then
    echo "$INPUT_STRING" | base64
else
    echo "$INPUT_STRING" | base64 --decode
fi

output of script:

[ec2-user@ip-10-252-34-162 ~]$ ./test.sh
ZEdWemRGOXpkSEpwYm1jSwo=

the 'else' statement not working. but follow command works fine

echo "$INPUT_STRING" | base64 --decode
a611155
  • 33
  • 4
  • Possible duplicate of [How to declare and use boolean variables in shell script?](https://stackoverflow.com/questions/2953646/how-to-declare-and-use-boolean-variables-in-shell-script) – Gonzalo Matheu Apr 20 '18 at 01:04
  • @a611155 : Note that `[ false ]` evaluates to true, in the same way that `[ foobarbaz ]` evaluates to true. From the viewpoint of the `[` command, any non-empty string is true. – user1934428 Apr 20 '18 at 06:07

1 Answers1

0

Comparing your variable as strings works. I.e:

if [ "$ENCODING" == "false" ];
Gonzalo Matheu
  • 8,984
  • 5
  • 35
  • 58
  • thanks a lot. It works like magic.You saved me a lot of time. Why didn't the code work? Can you give me a keyword I can search for or a link to a referenced document? – a611155 Apr 20 '18 at 00:49
  • In http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html you can find the basics of *if* construct and its operators. – Gonzalo Matheu Apr 20 '18 at 01:11