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.

TAROUTPUT=$(tar -cf arch.tar /path/to/dir 2>&1)
  • Yes, working, thanks. Will accept answer in a minute – Miloš Đakonović May 20 '18 at 12:15
  • @HaukeLaging: This puts stdout and stderr together into TAROUTPUT. If I understood the OP correctly, he wants to collect stdout and stderr into different variables. – user1934428 May 21 '18 at 6:24
  • 1
    @user1934428 That's not how I understand "TAROUTPUT (with both stdout&stderr)" – Hauke Laging May 21 '18 at 8:48

If you want to separate stdout from stderr:

craft@engine:~$ tar -cf arch.tar /path/to/dir 1>/tmp/tar_stdout 2>/tmp/tar_stderr; RETCODE=$( echo ${?} );
craft@engine:~$ stdout_var=$( cat /tmp/tar_stdout )
craft@engine:~$ stderr_var=$( cat /tmp/tar_stderr )
craft@engine:~$ echo -e "STDOUT : ${stdout_var}\nSTDERR : ${stderr_var}\nCommand Status: ${RETCODE}"
  • 1>/tmp/tar_stdout : save the stdout output to a temp file.
  • 2>/tmp/tar_stderr : save stderr output to a file.
  • Return code of the command (exit status) is saved into the ${?} variable.

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.