将Shell脚本中的Echo输出重定向到日志文件

41

我有一个包含很多echo的shell脚本,我想将输出重定向到日志文件中。 我知道可以使用命令cmd > logfile.txt或在文件中执行echo 'xy' > logfile.txt来完成此操作,但是否可以在脚本中设置文件名,让所有的echo自动写入该文件呢?


2
你想要重定向仅限于 echo 吗?还有其他产生输出的命令吗? - Karoly Horvath
除echo之外没有其他输出 - wasp256
我认为这是我第一次给问题点赞并点赞了其中3个答案。一切都很好。社区做得很好! - DrBeco
6个回答

59

您可以将此行添加到脚本顶部:

#!/bin/bash
# redirect stdout/stderr to a file
exec >logfile.txt 2>&1

或者,要仅重定向标准输出,请使用:

exec > logfile.txt

7
我想将日志写入文件并在控制台上显示,你能告诉我应该使用什么吗? - Sandeep Singh
1
我尝试过这个命令exec > myLog.log 2>&1 | tee myLog.log,它能在控制台上显示但无法写入文件。我还试过command | tee file.log,但这也只能在控制台上显示。 - Sandeep Singh
它只在文件中写入系统日期。 - Sandeep Singh
这就是我们使用的命令的所有输出。好的,最好不要在不相关的问题上延长聊天会话。 - anubhava
1
Bashism中的&>在这里相当多余; 便携式符号>logfile.txt 2>&1更加明确,而且我认为更易读和更便携(并且容易更改为>>,而&>>是比较近期才引入的,在仍然只提供Bash 3的平台上无法使用,例如macOS)。 - tripleee
显示剩余4条评论

25

我尝试使用以下命令进行管理。这将把输出写入日志文件并打印到控制台。

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

请注意:这是Bash代码,如果你使用sh运行它,将会抛出语法错误。


那么我怎样才能追加而不是覆盖呢?或者因为我们也要输出到屏幕,所以无法这样做?(我尝试修改了一行代码为“exec >> >(tee..”,但它仍然覆盖之前的内容) - Mark Smith
2
@MarkSmith 请使用 -a 选项:exec > >(tee -a $log) - Sandeep Singh
当然!我有点知道使用tee的-a选项,但是完全忘记了。谢谢。 - Mark Smith
以上代码完美运行;但是好奇的是,有人能解释一下为什么会这样吗? - Kelly Trinh
@Kelly 符号 >(cmd) 实际上创建了一个并行进程,该进程在包含此进程替换的命令的持续时间内运行 cmd,并将其输出重定向到 cmd 的标准输入。在这里,命令 exec 是一个特殊情况;它的唯一目的是创建一个进程替换,直到脚本结束或下一个 exec 将相同的文件描述符重定向到不同的目标为止。 - tripleee

14

你可以使用子shell轻松地将Shell脚本的不同部分重定向到一个文件(或多个文件)中:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

5
LOG_LOCATION="/path/to/logs"    
exec >> $LOG_LOCATION/mylogfile.log 2>&1

4
#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"

输出:

> ./above_script.sh                                                                
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file

在这里阅读更多内容:http://www.tldp.org/LDP/abs/html/io-redirection.html


ABS是一个相当可疑的参考资料;最好链接到官方Bash参考手册或POSIX。 - tripleee

2

要在控制台上获取输出并将日志输出到文件中:

script.sh

#!/bin/bash
(
  #Command 1
  #Command 2
  #Command 3
  ...
) 2>&1 | tee /path/to/save/console_output.log

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接