0

I'm new using environment variables and i'm testing how to pass and override environment vars to my scripts.

To test its behaviour, i've created a simple trivial script named testenv.sh as follow:

#!/bin/bash echo $COLOR 

So, when i run

$ env COLOR=RED ./testenv.sh 

I get the expected stdout RED.


However my question is, why if i run the following command

$ env COLOR=RED echo $COLOR 

I don't get the same result as above, in fact is a blank stdout.

1

1 Answer 1

4

$COLOR is expanded by the shell before env calls /bin/echo.

This cannot work unless you let env call a shell script that expands the variable.

Even:

COLOR=RED echo $COLOR 

does not work as you expect since Shell Variables are expanded before the new environment is set up.

You need to split this into two lines:

COLOR=RED echo $COLOR 

to make it work as you expect.

If you call:

env COLOR=RED sh -c 'echo $COLOR' 

it works because the single quotes prevent variable expansion and the variable expansion is delayed for the time when the new shell is run with the new environment.

4
  • @schily it didn't work yet, the echo still prints a blank stdout because env vars are ephemerals Commented Nov 21, 2019 at 16:56
  • The answer written by @roaima really works. Commented Nov 21, 2019 at 16:56
  • 1
    @Juan-Kabbali You did not read my answer. Before the last edit, I did not post any working example based on env. Commented Nov 21, 2019 at 17:09
  • yeah ! so the functional example was using shell vars and not env. It works ! Commented Nov 21, 2019 at 17:24

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.