フォーマットの問題

フォーマットの問題

以下のような小さなスクリプトがあり、問題が発生した場合、出力は画面上に赤、黄色などで強調表示されます。

normal=$(tput sgr0)
red=$(tput setaf 1)
yellow=$(tput setaf 3)

df -h >/dev/null 2>&1 &
xx_pid=$!
sleep 3
if [ `ps -ef| grep $xx_pid | grep -v grep | wc -l` -gt 0 ]; then
kill $xx_pid > /dev/null 2>&1
 printf "%-70s %s\n" "${red}df -h response : "  "  ......... taking more  than 30 Seconds to complete, exiting script${normal}" | tee -a $log
 exit
else
 printf "%-70s %s\n" "df -h response : "  " ......... NORMAL (Completed in  less than 30sec)" | tee -a $log
 fi

ただし、ログファイルには次のジャンク文字が表示されます([31mと(B [m))

[31mdf -h response :                    ......... taking more than 30 Seconds to complete, exiting script(B[m

ログファイルに書き込まずにこれらのジャンク文字を防ぐ方法はありますか?

ベストアンサー1

使用する必要はありませんtee。メッセージを変数に割り当て、printf それ色を使って、それからログファイルにメッセージを追加します。

 msg=$(printf "%-70s %s" "df -h response : "  " ......... NORMAL (Completed in >
 printf "%s%s%s\n" "${red}" "$msg" "${normal}"
 printf "%s\n" "$msg" >>$log

代わりに

 printf "%-70s %s\n" "${red}df -h response : "  "  ......... taking more  than 30 Seconds to complete, exiting script${normal}" | tee -a $log

問題は、tee標準出力にのみ書き込むことができることです。あなたできるstdoutを別々にリダイレクトするには、スクリプトで何かを行う必要がありますが面倒です。

 ( printf "%-70s %s\n" "df -h response : "  "  ......... taking more  than 30 Seconds to complete, exiting script" | tee -a $log ) | sed -e "s/^/${red}/" -e "s/$/${normal}/"

おすすめ記事