I have a program that asks the user for input and provides interactive features such as moving the cursor, deleting text, and more. After the user completes entering the input, the program clears the input line completely and prints the user query to stderr. To enable the interactive features, the terminal is put in raw mode and escape sequences are used.
I want to capture the stderr output of this program into a variable without interfering with its stdout (i.e. without messing up the interactive feature). Most solutions recommend something like program 2>&1 1>/dev/null | read query
, but this destroys the stdout and overwrites it with the stderr. The closest I could manage to get was to write to a temporary file and then use read
on it like so:
program 2> tempfile.txt; read query < tempfile.txt
I'm looking for a solution that avoids using temporary files and directly pipes the stderr into the read
command's stdin (or captures the stderr into a variable some way without messing up the stdout). For example in fish
shell this can be done like so (as mentioned in the docs):
program 2>| read query
How can I achieve the same in bash? Is there an easier solution for zsh?
sudo echo > /dev/null
. You'll see it asks for the password even though stdout is redirected to/dev/null
. That's because this prompt goes to stderr. If it went to stdout, you wouldn't have seen the prompt asking for the password, and you won't understand why yoursudo
command is stuck. – aviro Jul 03 '23 at 09:49