我嘗試寫各種造型選項,允許着色和使用重定向造型慶典的彩色輸出庫。擊試驗,怪異的行爲
例如
echo "Red" | red
輸出紅色文本
和
echo "Bold" | bold
輸出粗體文字
和
echo "Yellow bold" | yellow | bold
輸出大膽的黃色文字
我寫了到目前爲止的代碼如下:
#shellcheck shell=bash
# set debug
# set -o xtrace
# number of colors supported
__colors=$(tput colors 2> /dev/null)
# colors
__black="$(tput setaf 0)"
__red="$(tput setaf 1)"
__green="$(tput setaf 2)"
__yellow="$(tput setaf 3)"
__blue="$(tput setaf 4)"
__magenta="$(tput setaf 5)"
__cyan="$(tput setaf 6)"
__white="$(tput setaf 7)"
# style
__default="$(tput sgr0)"
__bold="$(tput bold)"
__underline="$(tput smul)"
function has_colors() {
COLOR=${COLOR:-auto}
if [[ $COLOR = 'never' ]]; then
return 1
elif [[ $COLOR = 'always' ]]; then
return 0
else
# check if stoud is terminal and terminal supports colors
[[ -t 1 ]] && \
[[ -n $__colors ]] && \
[[ $__colors -ge 8 ]]
fi
}
function __style() {
read -r input
if has_colors; then
echo -e "$1" "$input" "$__default"
else
echo -e "$input"
fi
}
function black() {
__style "$__black"
}
function red() {
__style "$__red"
}
function green() {
__style "$__green"
}
function yellow() {
__style "$__yellow"
}
function blue() {
__style "$__blue"
}
function magenta() {
__style "$__magenta"
}
function cyan() {
__style "$__cyan"
}
function white() {
__style "$__white"
}
function bold() {
__style "$__bold"
}
function underline() {
__style "$__underline"
}
設置COLOR =總是與轉義碼輸出所有的時間。另一方面,COLOR = auto會執行一些檢查,以確保當前stdout是終端並且終端支持顏色。
這個問題可以用多種造型方案似乎並不被working.It總是適用的最後一個造型的選擇。例如:
echo "Yellow bold" | yellow | bold
輸出大膽的文字,而不是黃色的。
在另一方面:
echo "Bold yellow" | bold | yellow
輸出黃色文字,而不是大膽。
有趣的是,設置COLOR =總是好像工作得很好。所以它看起來像我執行的測試,看看標準輸出是否是終端[[ -t 1 ]]
正在造成這種情況。我不確定是否因爲測試有某種延遲。但是當我刪除[[ -t 1 ]]
位時,它可以工作。
任何想法,我怎麼能做到這一點?不是Bash的專家,或者shell如何處理這個問題。很困惑在這裏。
的問題是,在'黃色|粗體','黃色'的標準輸出不是tty。而不是檢查每個顏色函數,你應該在主腳本中檢查一次,並設置一個變量,所有函數使用 –
@這個人,這正是我檢查它的原因。如果我檢查一次並將輸出重定向到一個文件,它將與顏色轉義碼一起使用。我不想要 – Bren
看着set -xv輸出,你的問題似乎來自這樣一個事實,即粗體(假設它是第二個)在樣式中的echo -e行之前被調用並接收到原始字符串的副本,因此,您可以在中間進行儘可能多的更改,並且結果始終爲標準文本粗體。不知何故,你需要讓每個管道依次接收數據(不確定最佳方法)。你可以看看等待命令? – grail