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?

2
  • Perhaps it is going to STDERR..Run VARABLENAME="$(command 2>&1)" and then check with echo "${VARIABLENAME}"..
    – heemayl
    Commented Jul 29, 2015 at 14:39
  • That did the trick! Can you please explain what that means? Also, resubmit it as an answer so I can accept it Commented Jul 29, 2015 at 14:44

1 Answer 1

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)"
3
  • +1 however technically speaking if there's no stdout you don't need to redirect it, so that could be still VARABLENAME="$(command 2>&1)" without wasting a redirection ;) I see what you meant, but maybe it needs rephrasing, such as "If you want to save only stderr than you can [...]"
    – kos
    Commented Jul 29, 2015 at 15:07
  • @kos Yeah..after thinking about that i have gone for generalization (taking no chances)..anyway clarified a bit more.. ;)
    – heemayl
    Commented Jul 29, 2015 at 15:14
  • What I meant is that if there's no stdout (as in "Also as there is no STDOUT [...]" <- this is what I was referring to) then the command might be just VARABLENAME="$(command 2>&1)" without using another redirection, just like in the previous case; I tought maybe you wanted to address a different case such as "Also if you don't want to store STDOUT [...]"
    – kos
    Commented Jul 29, 2015 at 15:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .