Bash

格式化幫助部分以在一列中包含標誌的描述

  • October 12, 2016

我創建了一個具有以下顯示的幫助部分

-m         This is a very very very very very very very very very very
very very very very very very very very very very long sentence

我想擁有

-m         This is a very very very very very very very very very very
          very very very very very very very very very very long 
          sentence.

指定我想要 2 列?

這是我整理的一個函式,您可以使用它一次列印一個與幫助相關的項目。我使用了-m問題中的範例和長幫助字元串。該函式將第一列的寬度硬編碼為 10,然後計算第 2 列的剩餘空間。

#!/bin/bash

function printhelp() (
 c1width=10
 cols=$(tput cols)
 c2width=$((cols - c1width - 1))
 readarray -t lines < <(printf '%s' "$2" | fmt -w $c2width)
 for((line=0; line < ${#lines[*]}; line++))
 do
   if [ $line -eq 0 ]
   then
     col1="$1"
   else
     col1=" "
   fi
   printf "%-${c1width}s %-${c2width}s\n" "$col1" "${lines[line]}"
 done
)

optf='-m'
optd='This is a very very very very very very very very very very very very very very very very very very very very long sentence'
printhelp "$optf" "$optd"

50 列螢幕上的範例輸出:

-m         This is a very very very very very
          very very very very very very very
          very very very very very very very
          very long sentence

在 80 列螢幕上:

-m         This is a very very very very very very very very very very very
          very very very very very very very very very long sentence

在 130 列螢幕上:

-m         This is a very very very very very very very very very very very very very very very very very very very very
          long sentence

在 150 列螢幕上:

-m         This is a very very very very very very very very very very very very very very very very very very very very long sentence

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