【问题标题】:Logs are not inserting in 'nohup.out' file日志未插入到“nohup.out”文件中
【发布时间】:2020-08-30 06:32:14
【问题描述】:

我正在通过 crontab 执行 script1.sh。

script1.sh

echo "Crontab is executing this script."
echo "Some code is running here."
cd cron
./script2.sh

“script1.sh”正在调用“script2.sh”。

'script2.sh'

echo "Exceuting script2."
echo "log of script3.sh is inserting in nohup.out file."
nohup sh script3.sh &
echo "Above syntax is not logging in nohup.out file. but this syntax is 'sh script3.sh > nohup.out &' is logging in nohup.out file. Why is it so?"

'script2.sh' 正在调用'script3.sh',但无法登录 nohup.out 文件。对于日志记录,使用以下语法。

nohup sh script3.sh &

'script3.sh' 包含下面提到的代码行。

echo "Executing script3. This is just test example to simulate the things."

为什么日志没有插入到 nohup.out 文件中?

【问题讨论】:

  • 您的问题不清楚。 “为什么日志没有插入 nohup.out 文件?” - 什么日志? “script3.sh”有什么作用?我们能看到吗?请提供一个可重现的最小示例。
  • @StephenC ...在实际场景中'script3.sh'将是应用服务器日志。
  • @user752590 :文本 Executing script3. ..... 应该在nohup.out. If it isn't, what else do you see in this file? Is ``nohup.out 中为空?您是否查看了正确 nohup.out,而不是之前运行的剩余文件(检查时间戳)?
  • @user1934428 ... "nohup.out 是空的吗?"... nohup.out 不存在。
  • crontab 不在交互式 shell 中运行,因此 crontab 没有标准输出或标准输入。这就是 crontab 中的 nohup 不生成 nohup.out 的原因。请使用重定向 &>1 来存储您的日志。阅读此stackoverflow.com/questions/14145250/…

标签: bash shell sh nohup


【解决方案1】:

来自info nohup

23.4 ‘nohup’:运行不受挂断影响的命令 ==============================================

‘nohup’ 运行给定的命令,忽略挂断信号,因此 登出后,该命令可以在后台继续运行。
...
如果标准输出是终端,则命令的标准输出是 附加到文件'nohup.out';
如果无法写入,[waltera:当前目录中的写入权限/空间]它是 附加到文件“$HOME/nohup.out”;如果那不能写 到,命令没有运行。
...
但是,如果标准输出关闭,标准错误终端输出 而是附加到文件“nohup.out”或“$HOME/nohup.out”作为 以上。

cron 执行脚本时,stdout 不是终端也不是关闭的,所以nohup 没有理由重定向任何输出。
另一个没有终端的nohup 中的demo 是当你启动你的script2.sh 时,它有一个nohup 命令和另一个nohup

nohup ./script2.sh > masternohup.out

script3.sh 的输出将写入masternohup.out

【讨论】:

    【解决方案2】:

    来自man nohup

    ...
    If standard input is a terminal, redirect it from an unreadable file.
    If standard output is a terminal, append output to 'nohup.out' if possible, '$HOME/nohup.out' otherwise.
    If standard error is a terminal, redirect it to standard output.
    To save output to FILE, use 'nohup COMMAND > FILE'.
    ...
    

    所以它可以在$HOME/nohup.out 中,最好用它来控制输出:

    nohup COMMAND &> FILE
    

    【讨论】:

    • 如果我独立运行“script2.sh”(没有 crontab),日志将插入 nohup.out 文件中。但是当我通过 cronjob 执行时,它不会产生 nohup.out 文件。
    • 这个答案听起来很合理;如果标准输出不是 TTY;它是例如一个文件(不能确定 cron ......),然后 nohup 不会(重新)重定向标准输出,而只是保持当前写入标准输出的位置......虽然这可能是特定于 bash 的(并且&> 重定向在交互式使用),我建议在将 stdout 和 stderr 重定向到同一个文件时使用1> FILE 2>&1
    【解决方案3】:

    你现在不需要nohup

    Shell 转义方法允许进程离开其进程组,并且永远不会收到SIGHUP 或任何其他指向进程组的信号。

    在 bash 外壳中:

    (command &>log.txt &)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 2016-05-08
      • 2012-11-11
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多