2

This command works as expected

> TEST=`uuidgen` sh -c 'echo "$TEST"'
BE6DFB7B-D872-49D7-91E6-24D01644B0A2
> 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"'                                          
52EFFEAA-D094-4FC3-8212-6A294918E265
[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?

2

You could run both commands with the same shell:

TEST=`uuidgen` sh -c 'echo "$TEST" && echo "$TEST"'
| improve this answer | |
  • 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. – Klas Mellbourn Oct 21 '19 at 17:40
0

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

$ export TEST="coincoin"
$ echo $TEST
coincoin
$ cat test.sh 
#!/bin/bash

echo "Test is ${TEST}"
$ ./test.sh 
Test is coincoin
| improve this answer | |
  • No, I don't want to make it an exported variable, I want it to live just for the duration of the line – Klas Mellbourn 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. – Gordon Davisson Oct 21 '19 at 19:25
0

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"
    NEWTEST="$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.

    e.g.

    export TEST=foo
    

    or:

    TEST=foo
    export TEST
    
| improve this answer | |

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.