5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What is the difference between BRANCH='test' bash -c 'echo "$BRANCH"' and BRANCH='test' echo "$BRANCH"?
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.
I guess this answer explains it well.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.