stderr 重定向导致读取命令不打印输出

stderr redirection is causing read command to not print output

代码为

#!/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>&-

我试图恢复 exec 1>&3 所以读取是回声但是当我正常时它不显示 echo "hello" 它显示但不显示 read.

对于我希望用户干预的代码中的选择性位置,我恢复了输出处理,但脚本等待命令输入然后执行。

您希望 read 打印到 stdout,但它打印到 stderr,如下命令所示:

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

看看你的/tmp/stderr.log。缺少的提示会在里面。

要恢复 read 打印到屏幕的能力,而不是恢复 stdout,您需要恢复 stderr:

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

或者,如评论中所述,您可以只为 read 命令恢复它,而不是使用单独的命令恢复 stderr

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