11

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.

    2 Answers 2

    11
    TAROUTPUT=$(tar -cf arch.tar /path/to/dir 2>&1) this_is_the_tar_exit_code=$? 
    3
    • Yes, working, thanks. Will accept answer in a minuteCommentedMay 20, 2018 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.CommentedMay 21, 2018 at 6:24
    • 2
      @user1934428 That's not how I understand "TAROUTPUT (with both stdout&stderr)"CommentedMay 21, 2018 at 8:48
    3

    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.

      You must log in to answer this question.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.