如何重定向脚本的完整输出 [英] how to redirect complete output of a script

查看:209
本文介绍了如何重定向脚本的完整输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的cronjob每天在18:35运行:

I have a simple cronjob running every day at 18:35:

05 18 * * * ~/job.sh 2>&1 >> ~/job.log

因此〜/ job.sh的输出应写入〜/ job .log。在job.sh中,有一些echo命令和一些python脚本被执行,例如:

So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.:

echo 'doing xyz'
python doXYZ.py



现在,无论python脚本产生什么输出, 〜/ job.log。我只看到echo /文本〜/ job.log。如何将shell脚本的完成输出重定向到〜/ job.log?

Now, whatever output the python scripts produce, they are not written into ~/job.log. I only see the echo text in ~/job.log. How can I redirect the complete output of the shell script to ~/job.log?

推荐答案

Arkaitz有最简单的解决方案。但是,要查看您的代码段出了什么问题,我们需要进入bash手册:

Arkaitz has the simplest solution. However, to see what's wrong with your snippet we need to go into the bash manual:


请注意,重定向顺序很重要。例如,
命令

Note that the order of redirections is significant. For example, the command

  ls > dirlist 2>&1

将标准输出和标准错误都定向到文件dirlist,
命令

directs both standard output and standard error to the file dirlist, while the command

 ls 2>&1 > dirlist

只将标准输出指向文件dirlist,因为标准
错误是从标准输出之前的标准输出
put被重定向到dirlist。

directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard out‐ put was redirected to dirlist.

所以显然输出重定向只重定向到 ,而不是其他流。当bash解析您的命令行时,它将出现在 2>& 1 子句中,并重定向 stderr stdout ,此时仍然是控制台(或任何附加到 cron stdout )。只有在此之后, stdout 才会被重定向。

So apparently the output redirection only redirects to the target of the other stream, not to the other stream itself. When bash parses your command line it will come upon the 2>&1 clause and redirect stderr to the target of stdout, which at this point is still the console (or whatever is attached to cron's stdout). Only after this will stdout be redirected.

所以你真正想要的是:

05 18 * * * ~/job.sh >>~/job.log 2>&1

这篇关于如何重定向脚本的完整输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆