Looked some for an answer, but not finding anything that sticks out as a solution.

I'm trying to make a bash script, and in it I need to save the output of git rev-parse --show-toplevel to a variable. When I run this command in my terminal it spits something to output.

Firstly, why does myVar=git rev-parse --show-toplevel not work in my script? The error I'm getting is rev-parse: command not found.

Secondly, I think I need to do something like myVar=${git rev-parse --show-toplevel}, but this is telling me it's a bad substitution.

Can anyone clarify these things for me, or link to stuff that is relevant? Would really appreciate it.


You need command substitution ($()) to save the output of a command in a variable:

myVar="$(git rev-parse --show-toplevel)"

Now to get the value of the variable myVar, use "$myVar".

  • Thanks for this. Exactly what I needed. Can you tell me about the double-quotes that you're using? I just changed my script, and am not using any quotes anywhere but am getting the correct behavior. When should I use quotes as you have? – noob-in-need Apr 13 '16 at 15:55
  • you can also use backticks myVar= `git rev-parse --show-toplevel` – mazs Apr 13 '16 at 16:00
  • Also, can you tell me if git rev-parse --show-toplevel would return a 0 or 1 (as an exit code) in addition to the text that it outputs? How would I capture the exit code instead of the output text if that were what I was after? – noob-in-need Apr 13 '16 at 16:01
  • @noob-in-need check unix.stackexchange.com/a/68748/68757 .. the exit status will remain the same to what would be without the variable.. – heemayl Apr 13 '16 at 16:16

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.