
這是我的嘗試:
最後一個有效,但它破壞了複製貼上(複製時添加了大量空格)。有沒有更好的辦法?
可複製文字:
$ PS1='\['$'\x1b[0m\]$ '
$ echo -e "\x1b[41;37mWarning text\x1b[0m"; echo Normal text
Warning text
Normal text
$ echo -ne "\x1b[41;37mWarning text"$'\n'"\x1b[0m"; echo Normal text
Warning text
Normal text
$ echo -ne "\x1b[41;37mWarning text"$'\n'"\x1b[47;30m"; tr </dev/zero \\0 \ |head -c 80; echo -ne "\x1b[A"; echo Normal text
Warning text
Normal text
$
$ t="Warning text";echo -ne "\x1b[41;37m";echo -n "$t";{ tr </dev/zero \\0 \ |head -c $(bc <<<"$(stty -a <&3|grep -Po '(?<=columns )[0-9]+')-$(wc -c<<<"$t")+1"); } 3<&0;echo -e "\x1b[0m";echo "Normal text"
Warning text
Normal text
$
答案1
我自己找到了解決方案(在這個相關問題)。用這個:
echo -e '\x1b[41;37mWarning text\x1b[K\x1b[0m';echo Normal text
該文檔說\x1b[K
:
K EL Erase line (default: from cursor to end of line).
ESC [ 1 K: erase from start of line to cursor.
ESC [ 2 K: erase whole line.
答案2
清除到行尾將使用 xterm 和 Linux 控制台以及複製該行為的終端的當前背景顏色。在 ncurses 中,這稱為背景顏色擦除 (bce) 功能。當支援該功能時,這提供了一種使當前編輯的行的背景保持給定顏色的方法。
然而:
- 編輯換行時它的用處不大。
- 與 rxvt/urxvt 終端機有一些差異:相關的擦除字元 (ech) 功能不使用背景顏色。您的 shell 在編輯行時可能會使用它。
- 並非所有終端機在捲動時都使用目前背景顏色(如 xterm 和 Linux 控制台那樣)。
延伸閱讀:
答案3
這個怎麼樣:
printf '\e[41m%-*s\e[0m\n' $COLUMNS 'Warning text'
您也可以將其設為接受參數、新增顏色變數等的函數:
linecolor () { printf '\e[41m%-*s\e[0m\n' $COLUMNS "$1"; }
用法:
linecolor 'Warning text'
答案4
如果額外的初始空白行是可以接受的:
echo -e "\x1b[41;37m\n\x1b[0m\x1b[41;37mWarning\x1b[0m"; echo "Normal"
似乎有效。
對於我所看到的行為,我能想到的唯一解釋是,它取決於終端如何確定新行使用哪種背景顏色,如果您使用與我xterm
使用的不同的終端,那麼它的工作方式可能會有所不同。
我認為使用printf
使你最後一個方法更具可讀性,所以即使這仍然破壞複製粘貼,這裡是:
printf "\x1b[41;37m%-$(stty size | cut -d' ' -f2)s\x1b[0m\n" hello; echo world; echo test