Note that there are some explanatory texts on larger screens.

plurals
  1. POposix shell: stdout to file, exitcode to a variable and last line of stderr to another variable
    primarykey
    data
    text
    <p>I implemented the following in POSIX shell (not bash):</p> <p>fail.sh:</p> <pre><code>#!/bin/sh echo something useful echo warning 1 &gt;&amp;2 echo warning 2 &gt;&amp;2 echo an error message &gt;&amp;2 exit 100 </code></pre> <p>The command prints something I want to use on stdout, some warnings on stderr and an error message on stderr as well before failing with exit code 100.</p> <p>success.sh:</p> <pre><code>#!/bin/sh echo something useful echo warning 1 &gt;&amp;2 echo warning 2 &gt;&amp;2 exit 0 </code></pre> <p>This command prints something to stdout and some warnings to stderr but finishes successfully with exit code 0.</p> <p>test.sh:</p> <pre><code>#!/bin/sh -e script=$1 rm -f success msg=$({ $script &gt; useful; touch success; } 2&gt;&amp;1 | tail -1;) if [ -f success ]; then echo success else echo failure echo last error was: $msg fi </code></pre> <p>In this script I want to run either of those two scripts and provide the following functionality:</p> <ul> <li>the output of the scripts must be redirected to a file</li> <li>the last line of stderr must be saved to a variable so that I can print that last line later in case the command didnt exit successfully</li> <li>I want to detect whether or not the command exited successfully by checking its exit status</li> </ul> <p>My script test.sh achieves all of that but it uses an external file. Since I use <code>-e</code> the <code>touch</code> will only be executed if <code>$script</code> executed successfully. Can I capture the exit code of <code>$script</code> without this technique?</p> <p>The script must be written in POSIX shell and must use <code>-e</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload