This command works as expected

> TEST=`uuidgen` sh -c 'echo "$TEST"'
> echo $TEST
[empty line]

It sets the TEST variable locally on the command line and it is echoed by the echo command. After this line is executed, TEST is no longer set.

This however

> TEST=`uuidgen` sh -c 'echo "$TEST"' && sh -c 'echo "$TEST"'                                          
[empty line]

has the TEST variable set for the first command, but not the command after the &&. I want it to be set for both commands. What is the best way to achieve this?


You could run both commands with the same shell:

TEST=`uuidgen` sh -c 'echo "$TEST" && echo "$TEST"'
  • I would prefer not to use that method, in my actual case I'm running two yarn not sh. Running two yarn inside sh seems inelegant. Oct 21 '19 at 17:40

If you don't want a variable assignment to be temporary (i.e. for just one command) then make the assignment on a separate line.

Some examples of different kinds of variable assignments:

  1. TEST=foo echo "$TEST"

    This will temporarily assign the value foo to variable TEST (and temporarily export TEST) for ONLY that single echo command. Afterwards, it reverts to whatever value (and export status) it had before - unset if it had no value.

  2. TEST=foo
    echo "$TEST"

    In this example, TEST has the value foo until either the shell exits (e.g. logout or end of the script), or it is explicitly unset, or a new value assigned, so NEWTEST ends up with the same value (foo) as TEST.

    TEST is not exported, so is not available in the environment of programs executed from this shell.

  3. If you want the variable to be available in the environment of executed programs, you need to export it.


    export TEST=foo


    export TEST

Use export TEST=bla to make TEST variable for your whole shell session.

$ export TEST="coincoin"
$ echo $TEST
$ cat test.sh 

echo "Test is ${TEST}"
$ ./test.sh 
Test is coincoin
  • No, I don't want to make it an exported variable, I want it to live just for the duration of the line Oct 21 '19 at 17:39
  • @KlasMellbourn You could put the export and both commands in ( ), so they run under a subshell. But that'd also prevent other things (other variable settings etc) from affecting the main shell. Oct 21 '19 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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