如何根據 Bash 中的變數抑制 tee 的輸出

如何根據 Bash 中的變數抑制 tee 的輸出

因此,在下面的範例中:

echo "text to write to file but also not send to stdout" | tee -a $logfile 1> /dev/null

輸出不會列印在終端上。但是當我嘗試根據變數執行相同的操作時,它不起作用。

前任:

$loud=""
if [ -z $loud ]; then
  route_devnull="1> /dev/null"
else
  route_devnull=""
fi
echo "text to write to file but also not send to stdout" | tee -a $logfile $route_devnull

我怎麼能讓第二個例子起作用?或者我應該嘗試其他方法來抑制這些訊息?

答案1

長話短說:echo "text to write to file but also not send to stdout" | eval tee -a $logfile $route_devnull

bash不將變數作為命令進行計算。你可以寫

echo "abc && touch new"

它將列印abc && touch new到終端。這是設計使然,因為字串可以從使用者輸入,而且我們不想信任他們的命令,因為他們可以做惡意的事情,例如試圖破壞我們的電腦。

這是哪裡eval進來。

eval 不是先執行指令,而是讀取並評估建構另一個命令然後執行它的所有參數。例子:

eval echo "abc && touch new"

只需eval在執行前推入您想要評估的任何內容即可。我所說的“只是推”是指“仔細考慮使用eval

相關內容