簡體   English   中英

如何在bash中重定向所有stderr?

[英]How to redirect all stderr in bash?

我正在尋找一種方法來重定向交互式bash中的所有stderr流(理想情況下是它的調用父進程)。

我不想從每個單獨的命令重定向stderr流,我可以通過將2> a_file附加到每個命令來完成。

默認情況下,這些stderr流被重定向到交互式bash的stdout。 我想讓他們在這個交互式bash進程的stderr上,以防止我的stdout被錯誤消息污染,並能夠分開處理它們。

有任何想法嗎?

我還沒有找到答案......但也許它實際上是一個tty參數。 有沒有人知道關於處理stderr的tty / interactive shell責任?

使用bash中的exec內置:

exec 2> /tmp/myfile

您可以啟動一個新的bash進程重定向該進程的stderr:

  $ bash -i 2> stderr.log
  $ 

我發現一個好方法是用括號括起命令,'()',(啟動一個子shell)或大括號,'{}'(沒有子shell;更快):

{
  cmd1
  cmd2
  ...
  cmdN
} 2> error.log

當然,這可以在一行完成:

{ cmd1; cmd2; ... cmdN; } 2> error.log

兩件事情:

  1. 在遠程ssh命令中使用2>&1導致錯誤在本地tarfile中結束,從而導致“損壞”備份。
  2. 如果要在ssh的另一側應用重定向,請記住轉義重定向命令。

我的建議是將遠程端的stderr重定向到一個文件,並在出現錯誤時稍后再將其取出。

例:

ssh -t remotehost tar -cf - /mnt/backup 2\>backup.err > localbackup.tar
EXITSTATUS=$?
if [ $EXITSTATUS != "0" ] then 
  echo Error occurred!
  ssh remotehost cat backup.err >localbackup.errors
  cat localbackup.errors
  ssh remotehost rm backup.err 
else 
  echo Backup completed successfully!
  ssh remotehost rm backup.err 
fi

在雙引號中嘗試命令,如下所示:

ssh remotehost "command" 2>~/stderr

使用遠程主機上的不存在的文件在我的本地系統上測試。

$ ssh remotehost "tail x;head x" 2>~/stderr
$ cat stderr 
tail: cannot open `x' for reading: No such file or directory
head: cannot open `x' for reading: No such file or directory

我沒有看到你的問題按設計工作:

$ ssh remotehost 'ls nosuchfile; ls /etc/passwd' >/tmp/stdout 2>/tmp/stderr 
$ cat /tmp/stdout  
/etc/passwd 
$ cat /tmp/stderr 
nosuchfile not found

試過ssh -t在遠端創建一個偽TTY?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM