Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store the output of a git command in a variable?

Tags:

linux

bash

shell

What I want is to store the output of a git command (such as git status) inside a variable in a shell script. When I say output, I am talking about the text returned in the terminal on execution of a command, for example: on doing a git status outside my repo:

fatal: Not a git repository (or any of the parent directories): .git 

I tried this:

var=$(git status) 

But 'var' did not store anything.

like image 600
aliasav Avatar asked Jan 28 '15 06:01

aliasav


People also ask

How do you save a command output 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 ...]

Which command is used to save source code to Git?

Git clone Git clone is a command for downloading existing source code from a remote repository (like Github, for example). In other words, Git clone basically makes an identical copy of the latest version of a project in a repository and saves it to your computer.

How to store the output of a Python command in a variable?

We just need to pass another parameter capture=true with local to store the output of a command in a variable. substring = "up-to-date" msg = local ("git pull", capture=true) if substring in msg: "do something" else: "do something else" If you are using a version of Python older than 2.6 you can use popen, like in the example below.

How to save the output of a command to a variable?

text processing - Save the output of a command to a variable - Unix & Linux Stack Exchange The command mid3v2 -l someFile.mp3 gives the following output for a file with name someFile.mp3 in mp3-format: IDv2 tag info for someFile.mp3 APIC=cover front, (image/jpg, 52016 bytes) TALB= Stack Exchange Network

How to get the output of a command from another command?

The first step is to understand that the output of a command could be received by other commands via a pipe, or, could be captured in a variable: cmd | next command ... etc var=$(cmd)

How do I pipe the output of a command to a file?

To pipe the output of a command to tee , printing to to your screen and saving it to a file, but appending it to the end of the file: This will append the output to the end of the file, just like the >> operator.


1 Answers

You can use:

var=$(git status 2>&1) 

i.e. redirect stderr to stdout and then capture the output.

Otherwise when for error messages are written on stderr and your command: var=$(git status) is only capturing stdout.

like image 105
anubhava Avatar answered Sep 27 '22 18:09

anubhava