avinashse
avinashse

Reputation: 1460

print value of environment variable from a file

Problem Description

In my Unix ksh system, I am having an environment variable A on doing

echo ${A}

I am getting the desired value which is hello.

I can check this value in

env | grep ${A}

output: A=hello

or in

printenv | grep ${A}

output: A=hello

Now I have a file file which contains the list of environment variables and I have to fetch the corresponding value.

Now what I tried just for only first value of the file.

  1. env | grep $(cat file | awk 'NR==1{print $1}') --shows nothing

  2. b=$(cat file | awk 'NR==1{print $1}')

    env | grep echo $b

  3. b=cat TEMP_ES_HOST_MAP | awk -F"|" 'NR==1{print $2 }' echo $b c=eval $b c=echo $b

Nothing seems to be working.

Thank you

Upvotes: 1

Views: 1662

Answers (2)

anubhava
anubhava

Reputation: 785721

You can use xargs:

awk -F '[$()]+' '{print $1$2}' envfile | xargs printenv

Where:

cat envfile
$(LANG)
$LINES
USER
HISTFILESIZE

Upvotes: 3

Etan Reisner
Etan Reisner

Reputation: 81012

If you are looking for the variable named A in the output from env and printenv then using grep ${A} is incorrect (and unsafe/does not work for variables of more than one word).

What you want for that is:

env | grep ^A=
printenv | grep ^A=

So assuming your file looks like this:

VAR1
VAR2
OTHER_VAR

and you want to search for those you could use something like this (assuming you have process substitution):

env | grep -f <(awk '{print "^"$0"="}' varfile)

Assuming you don't have process substitution (or you would rather a simpler solution, I do) you can do this:

env | awk -F = 'NR==FNR{a[$1]++; next} $1 in a' varfile -

Actually this should work too and is even simpler (assuming an awk with ENVIRON):

awk '$1 in ENVIRON {print $1"="ENVIRON[$1]}' varfile

Upvotes: 3

Related Questions