Bash

替代手錶支持顏色

  • December 9, 2020

我有一個phpunit帶有彩色輸出的命令 ( )。根據watch, 命令我應該能夠使用該--color標誌來允許顏色渲染通過。但是,這是行不通的。有沒有其他方法可以解決這個問題?

phpunit | cat沒用(表明這不是命令的問題,watch而是phpunit 命令的問題)。

作為替代方案,以下 bash 腳本方法對我很有用:

#!/bin/bash
while true; do
   (echo -en '\033[H'
       CMD="$@"
       bash -c "$CMD" | while read LINE; do 
           echo -n "$LINE"
           echo -e '\033[0K' 
       done
       echo -en '\033[J') | tac | tac 
   sleep 2 
done

用法:

$ botch my-command

這是我的實現,它是一個 bash 腳本,但很容易將其轉換為函式(將“退出”更改為“返回”)

#!/bin/bash

trap ctrl_c INT

function ctrl_c()
{
   echo -en "\033[?7h" #Enable line wrap
   echo -e "\033[?25h" #Enable cursor
   exit 0
}

function print_usage()
{
   echo
   echo '  Usage: cwatch [sleep time] "command"'
   echo '  Example: cwatch "ls -la"'
   echo
}

if [ $# -eq 0 ] || [ $# -gt 2 ]
then
   print_usage
   exit 1
fi

SLEEPTIME=1
if [ $# -eq 2 ]
then
   SLEEPTIME=${1}
   if [[ $SLEEPTIME = *[[:digit:]]* ]]
   then
       shift
   else
       print_usage
       exit 1
   fi
fi

CMD="${1}"
echo -en "\033[?7l" #Disable line wrap
echo -en "\033[?25l" #Disable cursor
while (true)
do

   (echo -en "\033[H" #Sets the cursor position where subsequent text will begin
   echo -e "Every ${SLEEPTIME},0s: '\033[1;36m${CMD}\033[0m'\033[0K"
   echo -e "\033[0K" #Erases from the current cursor position to the end of the current line
   BASH_ENV=~/.bashrc bash -O expand_aliases -c "${CMD}" | while IFS='' read -r LINE 
   do
       echo -n "${LINE}"
       echo -e "\033[0K" #Erases from the current cursor position to the end of the current line
   done
   #echo -en "\033[J") | tac | tac #Erases the screen from the current line down to the bottom of the screen
   echo -en "\033[J") #Erases the screen from the current line down to the bottom of the screen
   sleep ${SLEEPTIME}
done

引用自:https://unix.stackexchange.com/questions/33479