0

I have a environment variable called NAME

export NAME="xyz"

and inside a file test.txt , I have a line

name=$NAME

I read the file and assigned the line to a variable y

y=`cat test.txt`

Now I am printing the variable y

echo $y

How can I get an output of name=xyz instead name=$NAME?

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
Jobs
  • 101
  • 3
  • where is your `export NAME="xyz"`? – WEBjuju Jan 18 '18 at 15:31
  • export NAME="xyz" is in the bash shell session , name=$NAME is in the file – Jobs Jan 18 '18 at 15:33
  • have you [looked at this solution](https://unix.stackexchange.com/questions/158117/how-to-pass-environment-variables-to-a-non-interactive-shell-with-example)? – WEBjuju Jan 18 '18 at 15:35
  • Are you wanting to refactor and not use the exported environmental variable? Your problem is not entirely clear. – 111--- Jan 18 '18 at 15:36
  • That is not seems simple explanation for beginners like me – Jobs Jan 18 '18 at 15:37
  • @datUser i'm gathering that his env variable is not available in the shell script. i asked him where he set it, but the question was misunderstood. – WEBjuju Jan 18 '18 at 15:38
  • If the environmental variable is causing you grief, I would suggest trying something more simple like passing the value you need from the system as a shell argument, `./script.sh someArgument` and accessing it with `$1`. – 111--- Jan 18 '18 at 15:45
  • I don’t have a script file , Everything is done in a single bash shell – Jobs Jan 18 '18 at 15:47
  • This is not the problem of evronmwng variable scope , if you assign y=“name=$NAME” , and then if you print y . You will get name=xyz as result – Jobs Jan 18 '18 at 15:52

1 Answers1

2

I think you need to implement eval for this particular usage. I'll explain using the command line:

  1. export $ABC (as you export $NAME)

    $ grep ABC .bashrc
    export ABC="xyz"
    
  2. set the variable in your txt file

    $ cat test.txt
    name=$ABC
    
  3. set the $y variable to the output of cat test.txt

    $ y=`cat test.txt`
    
  4. eval $y

    $ eval $y
    
  5. now name is set:

    $ echo $name
    xyz
    
WEBjuju
  • 496
  • 2
  • 4
  • 13
  • thx @datUser for the edit – WEBjuju Jan 18 '18 at 16:21
  • Hi, What I need is, a string , name=xyz . envsubst is a solution , but I found some example where a file is given as argument to it. Can we give the variable $y as input to envsubst program – Jobs Jan 23 '18 at 10:39
  • You have not explained well why you need to do what it is you are doing. – WEBjuju Jan 23 '18 at 18:34
  • I have to read the line name=$NAME from a file and reaplce the env variable $NAME in it and would get a result of name=xyz (consider that value of NAME in env is xyz) as output. I am using this output to grep another string. – Jobs Feb 05 '18 at 05:21