4

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

5

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.

  • I don't get it will the backticks solution work, because the output of git branch is not one branch name but as I pointed out all the branch names. And what does awk do? – Sachin Mar 16 '12 at 16:53
  • @Sachin The awk code checks if a line begins with * (/^\* / is a regexp match, the regexp is what's between the slashes); if it does, it prints the second word on the line ($2). So the output of git branch | awk '/^\* / { print $2 }' is just master. – Gilles Mar 16 '12 at 23:26
3

There is also the xargs command.

xargs - build and execute command lines from standard input

So the above answer from @Useless would translate to:

git branch | sed -ne 's/\*//p' | xargs git pull --rebase origin
2

There are several ways. The simplest is with backtick substitution:

git pull --rebase origin `git branch | sed -ne 's/\*//p'`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.