1

In /etc/environment I have declared a variable "myvar" as:

myvar='abc$#abc'.

I need to use the varibale in a script. When I print the variable through the script, The string gets chopped off after '$' character.

echo $myvar

Result:

abc$.

Fix(But why is this working?):

When I include source /etc/environment in the script, the variable is retrieved correctly.

#!/bin/bash

echo $myvar
source /etc/environment
echo $myvar

Result:

abc$
abc$#abc

Why is this working? And how can I make it work without using source?

  • Looks like `myvar` declared with 'abc$' and after soucing it's getting desired value. Try this command `declare | grep myvar=` to check how `myvar` is declared. – Ivan Aug 07 '20 at 11:06
  • @Ivan not getting output for that. but `printenv myvar` also gives `abc$`. PS: never declared `myvar` anywhere else for sure. – Nikhil Singh Aug 07 '20 at 11:11
  • @jared_mamrot tried that. it prints `abc\$` – Nikhil Singh Aug 07 '20 at 11:13
  • 3
    [escape-hash-mark-in-etc-environment](https://unix.stackexchange.com/questions/97736/escape-hash-mark-in-etc-environment) should answer your question. – Vijay Aug 07 '20 at 11:19
  • Why would your second script print a value for the first `echo $myvar` if you never set it? How do you execute the script? – Benjamin W. Aug 07 '20 at 13:15
  • @BenjaminW. I have declared `myvar` in /etc/environment. PS: The above comment answered my question. – Nikhil Singh Aug 07 '20 at 13:20
  • Still not clear to me why your second script prints `abc$` first and not nothing. How is `myvar` declared at the point where you first `echo` it? There are no commands before the `echo` in the script. – Benjamin W. Aug 07 '20 at 13:21
  • Oh, I get it now. – Benjamin W. Aug 07 '20 at 13:23
  • Duplicate on SO: https://stackoverflow.com/q/56688407/3266847 – Benjamin W. Aug 07 '20 at 13:26

0 Answers0