4

I am trying to set a variable before calling a command in bash (on Mac):

BRANCH=test echo "$BRANCH"

But I get an empty echo.

printenv also has no other variable with the same name:

$ printenv | grep BRANCH
$

What am I doing wrong?

1 Answer 1

4

This is correct way:

BRANCH='test' bash -c 'echo "$BRANCH"'
test

To execute echo command you'll need bash -c to execute it after assignment.

4
  • What is the difference between BRANCH='test' bash -c 'echo "$BRANCH"' and BRANCH='test' echo "$BRANCH"? Commented Dec 15, 2014 at 10:49
  • You could also use: ( BRANCH='test' && echo "$BRANCH" ) I guess in first case assignment isn't processed unless bash -c forks a new sub-process.
    – anubhava
    Commented Dec 15, 2014 at 10:56
  • 1
    I guess this answer explains it well. Commented Dec 15, 2014 at 11:02
  • Two things to note: first, $BRANCH is expanded before echo starts, before echo could look in its environment. Second, echo ignores its environment anyway. There's no need or ability to use an environment variable here, so just use echo test.
    – chepner
    Commented Dec 15, 2014 at 15:57

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