Linux

僅在成功時隱藏 shell 命令的輸出?

  • June 11, 2021

隱藏 shell 命令的輸出通常涉及重定向 stderr 和 stdout。是否有任何內置工具或命令預設隱藏輸出但錯誤轉儲所有累積輸出?我想將其作為遠端ssh命令的包裝器執行。現在我讓他們使用重定向,但我不知道是什麼讓他們失敗了,而且他們太冗長了。

**編輯:**最後,我根據@Belmin 的回答創建了以下模板,我對其進行了一些調整,以從腳本中累積所有先前的命令,使用目前程序標識符,自動刪除日誌,並添加失敗紅色錯誤出現問題時的消息。在此模板中,初始silent包裝器將成功,然後第三個命令失敗,因為目錄已經存在:

#!/bin/sh

set -e

SILENT_LOG=/tmp/silent_log_$$.txt
trap "/bin/rm -f $SILENT_LOG" EXIT

function report_and_exit {
   cat "${SILENT_LOG}";
   echo "\033[91mError running command.\033[39m"
   exit 1;
}

function silent {
   $* 2>>"${SILENT_LOG}" >> "${SILENT_LOG}" || report_and_exit;
}

silent mkdir -v pepe
silent mkdir -v pepe2
silent mkdir -v pepe
silent mkdir -v pepe2

我會像這樣設置一個bash函式

function suppress
{
  /bin/rm --force /tmp/suppress.out 2> /dev/null; \
  ${1+"$@"} > /tmp/suppress.out 2>&1 || \
  cat /tmp/suppress.out; \
  bin/rm /tmp/suppress.out;
}

然後,您可以執行以下命令:

suppress foo -a bar

為此目的編寫腳本應該很容易。

像這個完全未經測試的腳本。

OUTPUT=`tempfile`
program_we_want_to_capture &2>1 > $OUTPUT
[ $? -ne 0 ]; then
   cat $OUTPUT
   exit 1
fi
rm $OUTPUT

另一方面,對於我作為腳本的一部分執行的命令,我通常想要比簡單地列印所有輸出更好的東西。我經常把我看到的東西限制在未知範圍內。這是我根據十多年前閱讀的內容改編的腳本。

#!/bin/bash

the_command 2>&1 | awk '
BEGIN \
{
 # Initialize our error-detection flag.
 ErrorDetected = 0
}
# Following are regex that will simply skip all lines
# which are good and we never want to see
/ Added UserList source/ || \
/ Added User/ || \
/ init domainlist / || \
/ init iplist / || \
/ init urllist / || \
/ loading dbfile / || \
/^$/ {next} # Uninteresting message.  Skip it.

# Following are lines that we good and we always want to see
/ INFO: ready for requests / \
{
 print "  " $0 # Expected message we want to see.
 next
}

# any remaining lines are unexpected, and probably error messages.  These will be printed out and highlighted.
{
 print "->" $0 # Unexpected message.  Print it
 ErrorDetected=1
}

END \
{
 if (ErrorDetected == 1) {
   print "Unexpected messages (\"->\") detected in execution."
   exit 2
 }
}
'
exit $?

引用自:https://serverfault.com/questions/607884