2
USER_UID=$1
echo 'generate_token("$USER_UID")'

I want output like

generate_token("1234567")

i tried multiple ways but didn't worked. it just print same line without value generate_jwt("$USER_UID")

2

1 Answer 1

5

When you use single quotes, it causes the shell to preserve the literal value of each character within the quotes. This means the $ will be treated as a literal $ character.

You should use double quotes:

USER_UID="$1"
echo "generate_token(\"$USER_UID\")"

From the bash man page, under the Quoting section:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.

For POSIX details on quoting, see here.

Example in an interactive shell:

$ USER_UID='foo'
$ echo "generate_token(\"$USER_UID\")"
generate_token("foo")

This will also work if USER_UID contains spaces:

$ USER_UID='var with spaces'
$ echo "generate_token(\"$USER_UID\")"
generate_token("var with spaces")
3
  • @JohnBollinger Thanks for pointing that out, I updated my answer to correctly add the double quotes in the output. Commented Jan 24, 2021 at 16:22
  • Works for me, though as a matter of style and to avoid the possibility of $USER_UID being subject to word splitting, I would personally use 'generate_token("'"$USER_UID"'")' or, better, "generate_token(\"$USER_UID\")". Commented Jan 24, 2021 at 16:24
  • echo "generate_token(\"$USER_UID\")" this worked fine.
    – bugCracker
    Commented Jan 24, 2021 at 16:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.