3

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?

Philidor
  • 40,933
  • 9
  • 84
  • 94
Gabriel Petrovay
  • 18,575
  • 19
  • 87
  • 153

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
  • 713,503
  • 59
  • 514
  • 593
  • 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