2018年5月10日

SHELL 下輸出貼齊的訊息


function getPosition {

    echo -ne "\033[6n"            # ask the terminal for the position
    read -s -d\[ garbage          # discard the first part of the response
    read -s -d R pos              # store the position in bash variable 'foo'
    Y=$(echo "$pos" | cut -d\; -f 1)
    X=$(echo "$pos" | cut -d\; -f 2)
}


## 以指定顏色在 TERMINAL 右側顯示指定內容
function showStatus {

    WIDTH=$(tput cols)

    COLOR=$1
    MSG=$2

    LENGTH=$(echo ${MSG} | wc -c)

    # 取得目前座標 X: col, Y: row
    getPosition

    NEW_POS=$(expr ${WIDTH} - ${LENGTH})
    REPEATE=$(expr ${NEW_POS} - ${X})
    printf '.%.0s' $(seq 1 ${REPEATE})
    echo -e "${COLOR}${MSG}${COLOR_RESET}"

}

COLOR_HIGHWHITE='\033[1;37m'

echo
echo -n "This is a Book"
showStatus "${COLOR_HIGHWHITE}" "[YES]"

以下是執行範例: