6

I am trying to create a script that syncs my computer with google drive using the grive tool. I would like to store the output of the grive command to a bash variable, but I can't seem to get it to work.

Some googling has taught me that command outputs can be saved to variables using the following syntax:

VARABLENAME=$(command)

and the output can be later printed by

echo ${VARIABLENAME}

However, the grive command seems to be an exception to this because when I use this syntax, it still prints out the output in the terminal and the contents of the variable is empty.

How I can store the output of grive in a variable properly?

1 Answers1

10

The problem was that grive command was outputting to the error stream, STDERR (File descriptor 2), which is normally used for passing error messages while the STDOUT (File descriptor 1) is used for showing actual (upon success) output of any program (strictly speaking).

I have not used grive, but according to your words the developer might have used STDERR only to show any messages from the command.

Now the command substitution you have used :

VARABLENAME=$(command)

will save the STDOUT of command to VARABLENAME, not STDERR. As a result the variable was empty and you were seeing messages on terminal.

I have suggested :

VARABLENAME="$(command 2>&1)"

this will save both the STDOUT and STDERR to the variable (in your case just STDERR as there is no STDOUT), So you would get desired result using echo "${VARIABLENAME}".

Also as there is no STDOUT you can save just the STDERR to the variable (generalization, true for any such program) :

VARABLENAME="$(command 2>&1 >/dev/null)"
heemayl
  • 93,925