68

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?

Mark Unsworth
  • 3,027
  • 2
  • 20
  • 21

3 Answers3

68

$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 to get the output of the git command into an environment variable like this:

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

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.

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
  • For those who care the `export EMR_CLUSTER_ID_HELPER=\`cat /mnt/var/lib/info/job-flow.json | jq -r ".jobFlowId"\`` command works on Amazon EC2-Instance. I just tried it out to use for myself to so that I could put the EMR Cluster ID into an environment variable. So use the `` they work well. Thanks Don Cruickshank – Kyle Bridenstine May 15 '18 at 00:36
  • In case of `git log --oneline -1` failure, `export GIT_HASH=...` **will not fail**. In some cases it may lead to bugs hard to spot (i.e. CI/CD pipeline execution). I would suggest following modification `GIT_HASH=$(git log --oneline -1) && export GIT_HASH=$GIT_HASH` – Paweł Dulęba Feb 24 '20 at 11:57
50

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)
Community
  • 1
  • 1
Michael Rush
  • 3,950
  • 3
  • 27
  • 23
2

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
Sohail Si
  • 2,750
  • 2
  • 22
  • 36