Gabriel
Gabriel

Reputation: 9432

Setting variables before command in bash

Whats the difference between:

GIT_TRACE=1 git push

and

GIT_TRACE=1; git push

The same do not behave the same, since the first really outputs tracing info while executing git push since it obviously checks if such variable is set (environment?).

Upvotes: 2

Views: 1454

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

GIT_TRACE=1 git push

GIT_TRACE=1 is added to the environment of the git push command. The variable assignment is only in effect for that command. It doesn't affect any subsequent commands.

GIT_TRACE=1; git push

A shell variable named GIT_TRACE is set to 1. Shell variables are distinct from environment variables. Child processes only see environment variables. They don't see shell variables. It's a subtle distinction. And because of it, git push doesn't see the setting and it has no effect.

Also, unlike above the variable continues to be set for the duration of the script.

To make the setting visible you need to export it, promoting the shell variable to an environment variable.

export GIT_TRACE=1; git push

If you don't want the variable to affect any other commands, you could then run both commands in a subshell. Variable assignments in a subshell are lost when the subshell ends.

(export GIT_TRACE=1; git push)

Of course, there's no reason you would do this since GIT_TRACE=1 git push does exactly the same thing but better (it doesn't fork a subshell).

Upvotes: 4

Related Questions