![](/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.