Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux Shell 腳本輸出文字顏色設定技巧:自訂函式讓訊息一目瞭然

編輯:關於 Linux

在 Shell 腳本中為輸出訊息加上顏色,能清楚區分資訊、警告、錯誤等層級,大幅提升可讀性。本文提供一個通用的 echocolor 函式,支援 8 種基本顏色,並附使用範例。

echocolor 函式定義

echocolor() {
    local color=$1
    shift
    case $color in
        black)  echo -e "\e[0;30m$@\e[0m" ;;
        red)    echo -e "\e[0;31m$@\e[0m" ;;
        green)  echo -e "\e[0;32m$@\e[0m" ;;
        yellow) echo -e "\e[0;33m$@\e[0m" ;;
        blue)   echo -e "\e[0;34m$@\e[0m" ;;
        purple) echo -e "\e[0;35m$@\e[0m" ;;
        cyan)   echo -e "\e[0;36m$@\e[0m" ;;
        *)      echo -e "\e[0;37m$@\e[0m" ;;
    esac
}

使用範例

cd "$(dirname "$(readlink -f "${0}")")"
echocolor purple ">> 當前目錄:${PWD}"
modname=$(grep 'obj-m' Makefile | awk '{print $3}') && modname=${modname/.o}
echocolor purple ">> 模組名稱:${modname}"
echocolor yellow ">> 卸載舊模組.."
adb shell rmmod ${modname}
echocolor yellow ">> 編譯中.."
make
echocolor yellow ">> 上傳檔案.."
adb push k860_words_count.ko /tmp/
echocolor yellow ">> 安裝模組.."
adb shell insmod /tmp/k860_words_count.ko
echocolor cyan ">> 輸出除錯訊息.."
adb shell cat /proc/kmsg | grep word

將函式放入 ~/.bashrc 或腳本開頭即可重複使用,讓終端機輸出更具辨識度。

Copyright © Windows教程網 All Rights Reserved