如何自定义nohup日志输出格式

nohup 命令用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行。默认情况下,nohup 会将程序的输出重定向到名为 nohup.out 的文件中。如果你想自定义日志输出格式,可以使用 shell 脚本或其他工具来实现。

以下是一个简单的示例,展示了如何使用 shell 脚本自定义 nohup 日志输出格式:

  1. 创建一个名为 custom_nohup.sh 的 shell 脚本文件:
#!/bin/bash

# 获取当前日期和时间
current_date=$(date '+%Y-%m-%d %H:%M:%S')

# 获取要运行的命令
command="$@"

# 将命令的输出重定向到自定义格式的日志文件
nohup sh -c "echo '[$current_date] Starting command: $command'; $command >> custom_nohup.log 2>&1" &
  1. 为脚本添加可执行权限:
chmod +x custom_nohup.sh
  1. 使用 custom_nohup.sh 脚本运行你的程序。例如,如果你想运行名为 my_program 的程序,可以这样做:
./custom_nohup.sh my_program

这将在后台运行 my_program,并将输出重定向到名为 custom_nohup.log 的文件中。日志文件的每条记录将以自定义的日期和时间格式开头。

你可以根据需要修改 custom_nohup.sh 脚本,以实现所需的日志格式和其他功能。

Both comments and pings are currently closed.

Comments are closed.

Powered by KingAbc | 粤ICP备16106647号-2 | Loading Time‌ 0.684