将shell脚本中的echo输出重定向到logfile

时间:2014-09-14 13:19:30

标签: shell stdout

我有一个包含大量echo的shell脚本。我想将输出重定向到日志文件。 我知道有一个命令调用cmd > logfile.txt,或者在文件echo 'xy' > logfile.txt中执行,但是是否可以在脚本中设置文件名然后自动将所有echo写入此文件?

5 个答案:

答案 0 :(得分:24)

您可以在脚本之上添加此行:

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

或者只重定向stdout使用:

exec > logfile.txt

答案 1 :(得分:14)

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

#!/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 ]"

答案 2 :(得分:8)

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

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

答案 3 :(得分:2)

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

答案 4 :(得分:0)

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

相关问题