2016-12-29 34 views
0

我有一個腳本在終端中運行以檢查日誌文件,然後使用「>」重定向到一個文件。它的工作原理是這樣如何將終端輸出重定向到沒有顏色代碼的文件

<script> > ~/log.txt 

但我的劇本有一些顏色標記象

print ("\033[0;34m$temp \e[0;30m"); 

當使用 「>」,文本文件將是:

^[[0;34m./a/a.log 
^[[0;30m^[[0;32mPASS^[[0m 
^[[0;34m./b/b.log 
^[[0;30m^[[0;32mPASS^[[0m 

我不想刪除配色方案,因爲當我運行在終端(沒有輸出到文件)時,很容易看到結果。 你能幫我嗎?

+0

您的腳本應該識別其標準輸出是否爲端子,並相應地打開和關閉顏色輸出。對於shell腳本,使用'test -t 1'。 –

+0

你能解釋更多細節嗎?當標準輸出是終端時,我不知道如何識別。我可以使用哪個變量或函數?我通常在csh中編寫腳本(Perl可以) – Thepro

+0

csh並不適合編寫腳本,建議切換到bash或類似的shell。 –

回答

0

以下是csh腳本的全色設置。只有標準輸出是終端時,輸出纔會着色。

#!/bin/csh -f 

set colornames = (black red green yellow blue magenta cyan white) 

# set up standard colour indices 
@ i = 0 
while ($i < 8) 
    @ cc = ($i + 1) 
    set $colornames[$cc] = $i 
    @ i++ 
end 

# test if the standard output is a terminal  
test -t 1 
if ($status) then 
    # it is not a terminal; colour aliases do nothing 
    alias FG 'echo >/dev/null' 
    alias BG 'echo >/dev/null' 
    alias BO 'echo >/dev/null' 
    alias NC 'echo >/dev/null' 
else 
    # it is a terminal; colour aliases output escape sequences, portably 
    alias FG 'tput setaf $\!:1' 
    alias BG 'tput setab $\!:1' 
    alias BO 'tput bold' 
    alias NC 'tput sgr0' 
endif 

# example usage 

set silly = `FG red ; BG green; BO` 
set normal = `NC` 

echo "${silly}hello${normal}, world" 

我不是一個很棒的csh專家,所以這可能會變得更加優雅。

相關問題