![](/img/trans.png)
[英]Linux stdout stderr redirect to file: different from terminal output
[英]“Ambiguous output redirect” trying to send both stdout and stderr to mailx from a command sent to at
我有一个名为test.sh的bash脚本,为了简单起见,将一行打印到stdout ,将一行打印到stderr 。
test.sh:
#!/bin/bash
echo "this is to stdout"
echo "this is to stderr" 1>&2
我想在晚上7点运行脚本test.sh ,但仅限于满足某些条件。 为此,我有一个名为schedule.sh另一个bash脚本,检查一些东西,然后提交命令at
稍后运行。
我希望test.sh ( stdout和stderr )的输出通过电子邮件发送给我。 我使用mailx
来做这个,所以我可以得到一个很好的主题名称。
此外,我想at
闭嘴。 没有来自at
输出at
因为它总是向我发送丑陋的电子邮件(没有主题行),如果at
产生任何输出。
schedule.sh:
#!/bin/bash
my_email="me@example.com" # Email is a variable
# Check some stuff, exit if certain conditions not met
echo "~/test.sh 2>&1 | mailx -s\"Cool title\" $my_email" | at 7:00 PM &> /dev/null
有趣的是,当我从cron
运行schedule.sh (用sh
运行脚本)时,它运行得很好。 但是,当我从终端手动运行schedule.sh时 (注意:我正在使用tcsh
), at
(不是mailx
)给我发电子邮件说
Ambiguous output redirect.
当schedule.sh是一个bash脚本时,我不确定为什么运行schedule.sh的shell会产生影响。
这是我在查看schedule.sh时的想法。 引号内的所有内容"~/test.sh 2>&1 | mailx -s\\"Cool title\\" me@email.com"
应该是at
的参数,并且at
运行时将该参数作为使用sh
的命令运行。 重定向2>&1 |
因此,是sh
的风格。
当我删除2>&1
并且只将test.sh的stdout传递给mailx
,它确实有效; 不过,我收到2封电子邮件:一个来自标准输出 mailx
和另一个从标准错误 at
。
是什么赋予了? 无论我从哪个shell调用它,我怎样才能使这个工作?
谢谢。
编辑:
uname -o
说我的操作系统是GNU/Linux
这是uname -a
如果它有帮助:
Linux [hostname censored] 2.6.9-89.ELlargesmp #1 SMP Mon Jun 22 12:46:58 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
当我使用at -c
检查at
内容at -c
,这是我看到的:
#!/bin/sh
# atrun uid=xxxxx gid=xxxxx
# mail username 0
# ...
SHELL=/bin/tcsh; export SHELL
# ...
${SHELL:-/bin/sh} << `(dd if=/dev/urandom count=200 bs=1 2>/dev/null|LC_ALL=C tr -d -c '[:alnum:]')`
~/test.sh 2>&1 | mailx -s"Cool title" me@example.com
我很难理解倒数第二行......这是使用$ SHELL还是/bin/sh
?
通过at
执行的命令是:
~/test.sh 2>&1 | mailx -s\"Cool title\" $my_email
at
命令的行为因系统而异。 在Linux上,使用/bin/sh
执行命令。 实际上,在我的系统(Linux Mint 14)上,它会输出一条警告消息:
$ echo 'printenv > at.env' | at 19:24
warning: commands will be executed using /bin/sh
在Solaris上,该命令由$SHELL
环境变量的当前值指定的shell执行。 在Solaris 9上使用我的默认shell为/bin/tcsh
的帐户,我得到:
% echo 'printenv > at.env' | at 19:25
commands will be executed using /bin/tcsh
job 1397874300.a at Fri Apr 18 19:25:00 2014
% echo 'printenv > at.env' | env SHELL=/bin/sh at 19:28
commands will be executed using /bin/sh
job 1397874480.a at Fri Apr 18 19:28:00 2014
鉴于at
的行为不一致(并且坦率地混淆),我建议让它只执行一个命令,在该命令中执行任何I / O重定向。 无论使用哪个shell执行命令,这都是确保命令正确执行的最佳方法。
例如(未经测试的代码如下):
echo '#!/bin/bash' > tmp.bash
echo "~/test.sh 2>&1 | mailx -s\"Cool title\" $my_email" >> tmp.bash
chmod +x tmp.bash
echo "./tmp.bash" | at 7:00 PM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.