Pipe output to environment variable export command

Sh

Sh Problem Overview


I'm trying to set a git hash value into an environment variable, i thought it would be as simple as doing this:

git log --oneline -1 | export GIT_HASH=$1

But the $1 doesn't contain anything. What am I doing wrong?

Sh Solutions


Solution 1 - Sh

$1 is used to access the first argument in a script or a function. It is not used to access output from an earlier command in a pipeline.

You can use [command substitution][1] to get the output of the git command into an environment variable like this:

export GIT_HASH=`git log --oneline -1`

However...

This answer is specially in response to the question regarding the Bourne Shell and it is the most widely supported. Your shell (e.g. GNU Bash) will most likely support the $() syntax and so you should also consider Michael Rush's answer.

But some shells, like tcsh, do not support the $() syntax and so if you're writing a shell script to be as bulletproof as possible for the greatest number of systems then you should use the `` syntax despite the limitations.

[1]: http://en.wikipedia.org/wiki/Command_substitution "command substitution"

Solution 2 - Sh

Or, you can also do it using $(). (see What is the benefit of using $() instead of backticks shell scripts?)

For example:

export FOO_BACKWARDS=$(echo 'foo' | rev)

Solution 3 - Sh

You can use an external file as a temporary variable:

TMPFILE=/var/tmp/mark-unsworth-bashvar-1
git log --oneline -1  >$TMPFILE; export GIT_HASH=$(cat $TMPFILE); rm $TMPFILE
echo GIT_HASH is $GIT_HASH

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark UnsworthView Question on Stackoverflow
Solution 1 - ShDon CruickshankView Answer on Stackoverflow
Solution 2 - ShMichael RushView Answer on Stackoverflow
Solution 3 - ShSohail SiView Answer on Stackoverflow