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?

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168

1 Answers1

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • What is the difference between `BRANCH='test' bash -c 'echo "$BRANCH"'` and `BRANCH='test' echo "$BRANCH"`? – Gabriel Petrovay Dec 15 '14 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 Dec 15 '14 at 10:56
  • 1
    I guess [this answer](http://stackoverflow.com/a/10938530/454103) explains it well. – Gabriel Petrovay Dec 15 '14 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 Dec 15 '14 at 15:57