当命令提示用户输入时,如何将命令的输出重定向到文件?

Aar*_*hen 7 linux bash redirection prompt

我有一个命令会提示用户进行一些输入,然后将结果输出到终端。我输入如下命令将输出重定向到一个文件:

$the_command > abc.txt
Run Code Online (Sandbox Code Playgroud)

但它不起作用。问题是没有提示,那些提示问题的文本输出到 abc.txt 不是我想要的结果。

Has*_*tur 3

您的命令有效并正确地将输出重定向到文件abc.txt
问题是您的脚本如何询问输入数据以及您如何运行该脚本?
让我们看两个例子:

# Script_1.sh                                     # 1
echo Please, enter your firstname and lastname    # 2
read FN LN                                        # 3
echo "Hi! $LN, $FN !"                             # 4
Run Code Online (Sandbox Code Playgroud)

# Script_2.sh                                     # 5
read -p "Enter a comment " CM                     # 6
echo  "You said $CM"                              # 7
Run Code Online (Sandbox Code Playgroud)

如果您运行,/bin/bash Script1.sh > abc.txt您将不会在 tty 上看到“请输入...”的问题。如果您从键盘给出预期的输入,您将在文件中找到第 #2 行和第 #4 行的输出abc.txt

如果运行,/bin/bash Script2.sh > abc.txt您将看到问题“输入注释”,但您将在文件中找到abc.txt仅第 7 行的输出。

注意:如果您在子 shell 中运行 Script2,sh

(bash Script2.sh 2>&1)> abc.txt
Run Code Online (Sandbox Code Playgroud)

您不会在 tty 上看到任何输出,并且会在abc.txt文件中找到所有输出。
如果你运行它

bash Script2.sh 2>ccc.txt 1>ddd.txt`
Run Code Online (Sandbox Code Playgroud)

您将在 中找到标准输出(第 7 行)ddd.txt和标准错误(第 6 行)ccc.txt


如果您只想重定向部分命令输出,则必须修改脚本。
实现此目的的方法之一是创建一个函数,在其中移动脚本中将生成有趣输出的部分(见下文)。然后,您可以从脚本的主要部分(最初是您移入该函数的代码)调用此函数,仅将该输出重定向到日志文件:

 Part_To_Redirect(){
     : # all that you want
 }

 # ... Main part of the script
 # point where it was the part that generates the output
 Part_to_Redirect "$@" > abc.txt   # this to store only that part in the file
 # Part_to_Redirect "$@" >> abc.txt  # this to append that part in the file
 # ...
Run Code Online (Sandbox Code Playgroud)

你甚至应该发现有用tee

将输出重定向到多个文件,将标准输入复制到标准输出以及作为参数给出的任何文件。

 the_command  | tee abc.txt       # To redirect Standard output
 or 
 the_command 2>&1 | tee abc.txt   # To redirect err in out and both in the file
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将在 tty 上获得命令的正常输出,但同时您将在日志文件中保存一份副本abc.txtread -p如果您像 script2 中那样使用调用,那么您的情况应该会很舒服the_command | tee abc.txt

注释和参考文献:

添加"$@"您可以将脚本的所有参数传递给函数。

您可能会发现从互联网上的许多来源阅读有关 bashredirection 的更多信息很有趣。