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

was*_*256 18 shell stdout

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

anu*_*ava 28

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

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt
Run Code Online (Sandbox Code Playgroud)

或者只重定向stdout使用:

exec > logfile.txt
Run Code Online (Sandbox Code Playgroud)

  • 我想写登录文件,也希望它出现在控制台上。你能指导我该怎么用吗? (4认同)

San*_*ngh 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 ]"
Run Code Online (Sandbox Code Playgroud)

  • @MarkSmith 请与 `-a` 选项一起使用:`exec >>(tee -a $log)` (2认同)

小智 8

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

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2
Run Code Online (Sandbox Code Playgroud)


小智 5

LOG_LOCATION="/path/to/logs"    
exec >> $LOG_LOCATION/mylogfile.log 2>&1
Run Code Online (Sandbox Code Playgroud)