ターミナルウィンドウでコマンドライン出力を非表示にする方法は?

ターミナルウィンドウでコマンドライン出力を非表示にする方法は?

以下は簡単なコードです。

#!/bin/bash -ef
echo "Hello" > log.txt #saving the output of this command log.txt
command1 #this command running and showing it is output in terminal
command2 > log.txt #saving the output of this command log.txt
command3 #this command running and showing it is output in terminal

スクリプトに多くのコマンドがある場合。特定のコマンドの出力を非表示にして、この出力を残りのコマンドの端末ウィンドウに表示させることはできますか?同時に、すべてのコマンドの出力をlog.txtに保存する方法(出力を表示するかどうか)

ベストアンサー1

次のように一時的に出力をファイルにリダイレクトできます。

exec 1> log.txt
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> /dev/tty # Redirect stdout back to your terminal

より一般的なアプローチ(stdoutが端末ではなく元の状態に復元したい場合):

exec 3>&1 # Point a new filehandle to the current stdout
exec 1> log.txt 
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> &3 # Restore stdout to what it originally was
exec 3> &- # Close the temporary filehandle

ありがとうセラーダの口コミこれを指摘してください。

おすすめ記事