如何在终端窗口中隐藏命令行的输出?

如何在终端窗口中隐藏命令行的输出?

下面是一个简单的代码:

#!/bin/bash -ef
echo "Hello" > log.txt #saving the output of this command log.txt
command1 #this command running and showing it is output in terminal
command2 > log.txt #saving the output of this command log.txt
command3 #this command running and showing it is output in terminal

如果我在脚本中有很多命令。我可以隐藏某些命令的输出并让此输出显示在终端窗口中以供其余命令使用吗?同时如何在 log.txt 中保存所有命令的输出(显示或不显示输出)

答案1

您可以暂时将输出重定向到文件,如下所示:

exec 1> log.txt
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> /dev/tty # Redirect stdout back to your terminal

更通用的方法(如果您的标准输出不是终端并且您想将其恢复到原来的状态):

exec 3>&1 # Point a new filehandle to the current stdout
exec 1> log.txt 
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> &3 # Restore stdout to what it originally was
exec 3> &- # Close the temporary filehandle

谢谢Celada 的评论指出这一点。

相关内容