Shell-Script

bash腳本,在框中回顯輸出

  • January 2, 2022

我創建了這個函式,它列印範例圖像中的輸出。但是,這個函式的實現似乎太複雜了。

有沒有辦法可以改進它或實施替代解決方案?

這是使用字元串參數“Love Unix & Linux”執行“box_out”函式後的輸出範例

#!/bin/bash
function box_out() {
   input_char=$(echo "$@" | wc -c)
   line=$(for i in `seq 0 $input_char`; do printf "-"; done)
   # tput This should be the best option. what tput does is it will
   # read the terminal info and render the correctly escaped ANSI code
   # for you.
   # Code like \033[31m will break the readline library in some of the
   # terminals.
   tput bold
   line="$(tput setaf 3)${line}"
   space=${line//-/ }
   echo " ${line}"
   printf '|' ; echo -n "$space" ; printf "%s\n" '|';
   printf '| ' ;tput setaf 4; echo -n "$@"; tput setaf 3 ; printf "%s\n" ' |';
   printf '|' ; echo -n "$space" ; printf "%s\n" '|';
   echo " ${line}"
   tput sgr 0
}

box_out $@

由於您的 shebang 和語法表明 unportable bash,我更喜歡這樣:

function box_out()
{
 local s="$*"
 tput setaf 3
 echo " -${s//?/-}-
| ${s//?/ } |
| $(tput setaf 4)$s$(tput setaf 3) |
| ${s//?/ } |
-${s//?/-}-"
 tput sgr 0
}

當然,您可以根據需要對其進行優化。

根據評論中的要求進行更新,以處理多行文本。

function box_out()
{
 local s=("$@") b w
 for l in "${s[@]}"; do
   ((w<${#l})) && { b="$l"; w="${#l}"; }
 done
 tput setaf 3
 echo " -${b//?/-}-
| ${b//?/ } |"
 for l in "${s[@]}"; do
   printf '| %s%*s%s |\n' "$(tput setaf 4)" "-$w" "$l" "$(tput setaf 3)"
 done
 echo "| ${b//?/ } |
-${b//?/-}-"
 tput sgr 0
}

使用多個參數呼叫它,例如box_out 'first line' 'more line' 'even more line'.

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