Bash – Execute command and store everything to variable in bash

bashexit-statusstderrstdout

In bash script I'm developing I'm trying to execute command and capture in variable(s):

  • stdout
  • stderr
  • status code

how to achieve that? The command is tar, if it is of any significance.

I tried the most standard approach:

TAROUTPUT=$(tar -cf arch.tar /path/to/dir)

Based on some work I did (I haven't actually produced tar failure) I get only stdout from this, stderr is not stored to variable. The perfect solution has TAROUTPUT (with both stdout&stderr) and TARSTATUS variables.

Thanks in advance.

Best Answer

TAROUTPUT=$(tar -cf arch.tar /path/to/dir 2>&1)
this_is_the_tar_exit_code=$?
Related Question