Execute command and store everything to variable in bash

15,228

Solution 1

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

Solution 2

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.
Share:
15,228

Related videos on Youtube

Miloš Đakonović
Author by

Miloš Đakonović

Web (HTML5/JavaScript, PHP) developer. System administrator. FOSS (mainly Linux and Postfix) advocate.

Updated on September 18, 2022

Comments

  • Miloš Đakonović
    Miloš Đakonović over 1 year

    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.

  • Miloš Đakonović
    Miloš Đakonović almost 6 years
    Yes, working, thanks. Will accept answer in a minute
  • Hauke Laging
    Hauke Laging almost 6 years
    @user1934428 That's not how I understand "TAROUTPUT (with both stdout&stderr)"