Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe output to environment variable export command

Tags:

sh

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?

like image 437
Mark Unsworth Avatar asked Mar 09 '14 20:03

Mark Unsworth


People also ask

How do you pipe the output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do I export an environment variable?

To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.

Which command can be used for print out all environment variables?

The most used command to displays the environment variables is printenv . If the name of the variable is passed as an argument to the command, only the value of that variable is displayed. If no argument is specified, printenv prints a list of all environment variables, one variable per line.


1 Answers

$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:

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.

like image 131
Don Cruickshank Avatar answered Sep 29 '22 08:09

Don Cruickshank