Let\'s say I have a script like the following:
useless.sh
echo \"This Is Error\" 1>&2
echo \"This Is Output\"
And I have an
Improving on YellowApple's answer:
This is a Bash function to capture stderr into any variable
stderr_capture_example.sh
:
#!/usr/bin/env bash
# Capture stderr from a command to a variable while maintaining stdout
# @Args:
# $1: The variable name to store the stderr output
# $2: Vararg command and arguments
# @Return:
# The Command's Returnn-Code or 2 if missing arguments
function capture_stderr {
[ $# -lt 2 ] && return 2
local stderr="$1"
shift
{
printf -v "$stderr" '%s' "$({ "$@" 1>&3; } 2>&1)"
} 3>&1
}
# Testing with a call to erroring ls
LANG=C capture_stderr my_stderr ls "$0" ''
printf '\nmy_stderr contains:\n%s' "$my_stderr"
Testing:
bash stderr_capture_example.sh
Output:
stderr_capture_example.sh
my_stderr contains:
ls: cannot access '': No such file or directory
This function can be used to capture the returned choice of a dialog
command.