0

I have the following bash script and seems the -n flag is always interpreted as string in echo

echo Hello, who am I talking to?
read login_name
login_name=$(echo -n $login_name | base64)
echo $login_name | base64 --decode

How do i correct that, or is there any other better syntax for my script?

Fan Cheung
  • 10,745
  • 3
  • 17
  • 39

1 Answers1

1

Better use more portable printf instead of echo -n and use read -p with correct quoting;

read -p 'Hello, who am I talking to? ' login_name
login_name=$(printf '%s' "$login_name" | base64)
printf '%s' "$login_name" | base64 --decode
echo

PS: Just to clarify that there is nothing special about using any flag inside $(...) so one can use it like this:

dt=$(date -u '+%Y/%m/%d')
echo "$dt"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • I need to encode without the line return from echo that’s why I added the -n, does ur code remove line break – Fan Cheung Nov 28 '19 at 08:02
  • Yes of course, `printf '%s'` doesn't print any newline – anubhava Nov 28 '19 at 08:03
  • But in general how do u execute with flags in $() – Fan Cheung Nov 28 '19 at 08:04
  • 1
    There is nothing special about `$(...)` here. One can use: `dt=$(date -u '+%Y/%m/%d')` – anubhava Nov 28 '19 at 08:06
  • just need to single quote the variable ? – Fan Cheung Nov 28 '19 at 08:09
  • For variables to expand we need to use double quotes otherwise single quote works better in other cases – anubhava Nov 28 '19 at 08:12
  • 1
    if you could add an answer to demonstrate how to add flag in $(), i'll mark +1 – Fan Cheung Nov 28 '19 at 08:15
  • 3
    @FanCheung It has nothing to do with `$( )`, and everything to do with `echo`. Some versions of `echo`, if their first argument starts with "-", interpret it as flags. Some don't. Basically, it's not safe to either try to pass flag options to `echo`, or to use it with a string that starts with "-". `printf` is more complicated to use, but much more predictable and controllable. – Gordon Davisson Nov 28 '19 at 08:22
  • 1
    thanks @GordonDavisson that really helps clearing the idea up – Fan Cheung Nov 28 '19 at 08:24