将shell脚本中的echo输出重定向到日志文件

jjhzyzn0  于 12个月前  发布在  Shell
关注(0)|答案(6)|浏览(180)

我有一个shell脚本,里面有很多echo。我想将输出重定向到一个日志文件。我知道有命令call cmd > logfile.txt,或者在文件echo 'xy' > logfile.txt中执行,但是否可以简单地在脚本中设置文件名,然后自动将所有echo写入该文件?

um6iljoc

um6iljoc1#

您可以在脚本的顶部添加这一行:

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

否则仅重定向标准输出用途:

exec > logfile.txt
dnph8jn4

dnph8jn42#

我试着使用下面的命令来管理。这将在日志文件中写入输出,并在控制台上打印。

#!/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运行它,它会抛出语法错误。

bq8i3lrv

bq8i3lrv3#

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

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

ohtdti5x4#

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

azpvetkf5#

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

qmelpv7a

qmelpv7a6#

要在控制台上获取输出并在文件中记录输出,请执行以下操作:

script.sh

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

相关问题