Search code examples
bashscriptingstderr

stderr redirection is causing read command to not print output


A code as

#!/bin/bash

exec 3>&1 4>&2
exec 1>/tmp/stdout.log
exec 2>/tmp/stderr.log
PS4='+ (Line $LINENO) '
set -x
echo "This goes to /tmp/stdout.log"
echo "This goes to /tmp/stderr.log" 1>&2
cmd1="$(uname -a)"
cmd2="$(uname +-a)"

exec 1>&3
read -n 1 -s -r -p "Please do manually Installation of package ,Press any key to continue"



exec 1>&3 2>&4
exec 3>&- 4>&-

I tried to restore exec 1>&3 so read is echo but its not showing when i do normal echo "hello" it shows but not with read.

For selective places in code where I want to user intervention I restore output handling but instead the script waits for command to enter and then execute.


Solution

  • You are expecting read to print to stdout, but it prints to stderr as demonstrated by this command:

    > read -p "prompt" 2>/dev/null # this command will print nothing
    

    Look in your /tmp/stderr.log. The missing prompt will be in there.

    To restore the ability of read to print to your screen, instead of restoring stdout, you need to restore stderr:

    exec 2>&4
    read -n 1 -s -r -p "Please do manually Installation of package ,Press any key to continue"
    

    Alternatively, as noted in the comments, instead of restoring stderr with a separate command, you can restore it just for the read command:

    read -n 1 -s -r -p "<shortened for clarity>" 2>&4