It can be done using the magic of file descriptors and the lastpipe
shell option.
It has to be done with a script - the "lastpipe" option will not work in interactive mode.
Here's the script I've tested with:
$ cat shorttest.sh
#!/bin/bash
shopt -s lastpipe
exit_tests() {
EXITMSG="$(cat /proc/self/fd/0)"
}
ls /bloop 2>&1 | exit_tests
echo "My output is \"$EXITMSG\""
$ bash shorttest.sh
My output is "ls: cannot access '/bloop': No such file or directory"
What I'm doing here is:
setting the shell option shopt -s lastpipe
. It will not work
without this as you will lose the file descriptor.
making sure my stderr also gets captured with 2>&1
piping the output into a function so that the stdin file descriptor can be referenced.
setting the variable by getting the contents of the
/proc/self/fd/0
file descriptor, which is stdin.
I'm using this for capturing errors in a script so if there is a problem with a command I can stop processing the script and exit right away.
shopt -s lastpipe
exit_tests() {
MYSTUFF="$(cat /proc/self/fd/0)"
BADLINE=$BASH_LINENO
}
error_msg () {
echo -e "$0: line $BADLINE\n\t $MYSTUFF"
exit 1
}
ls /bloop 2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg
In this way I can add 2>&1 | exit_tests ; [[ "${PIPESTATUS[0]}" == "0" ]] || error_msg
behind every command I care to check on.
Now you can enjoy your output!