Bash – How to pass output of one command as an argument to another

bashgitpipe

A similar question has been asked, but since I am new to Unix the answer was not clear to me due to the context. What I want to do is to pass the output of one command as an argument to another. I am using git for source control and working on three different branches.

Whenever I need to commit I have to check my branch and then give the corresponding command as

git pull --rebase origin <branch-name>

I wanted to write an alias as git-rebase and what it would do is that first it will execute git branch.

The output of git branch look like this

experiment
*master
new feature

So if we have two branches in addition to the master branch then it will show all the branches and the current branch will be star marked. I want to extract the star marked line and then pass the output of this to the above command.

Also I would like to suppress the output of the command git branch. I am not doing this because I am too lazy to type the whole command, but because I would like to learn more about the power of unix bash. Hoping to learn something from it

Best Answer

First, you need to massage the git branch output into a useable format

$ git branch
  experiment
* master
  new feature

$ git branch | awk '/^\* / { print $2 }'
master

Now, you want to use that as an argument:

$ git pull --rebase origin $(git branch | awk '/^\* / { print $2 }')

(or you can use backticks as in psusi's answer).

This should be ok, the awk command should always match exactly one line, and I'm assuming you can't have spaces in branch names. For anything much more complicated, I'd probably wrap it into a function (or a script) so you can do some sanity checking on the intermediate values.

Related Question