Linux

如何對齊最後一個欄位的輸出

  • December 21, 2018

bash 腳本

for i in $script_name
do
 echo -en "running the script - $i\t - "
 exec 3>&1 4>&2
 var=$( { time /tmp/scripts/$i 1>&3 2>&4; } 2>&1)  # Captures time only
 exec 3>&- 4>&-

 echo "$var"
done

列印以下內容:

running the script - Verify_disk.bash -       1.42
running the script - Verify_yum_list.bash - 10.49
running the script - Verify_size.bash -   2.93
running the script - Verify_mem_size.bash -       0.71
running the script - Verify_disk_size.bash -      2.41
running the script - Verify_wdisk.bash -        1.63
running the script - Verify_cpu.bash - 0.74

因為 $var 是列印所有這些輸出的變數,所以我們要對齊輸出

所以會是這樣

running the script - Verify_disk.bash        -   1.42
running the script - Verify_yum_list.bash    -   10.49
running the script - Verify_size.bash        -   2.93
running the script - Verify_mem_size.bash    -   0.71
running the script - Verify_disk_size.bash   -   2.41
running the script - Verify_wdisk.bash       -   1.63
running the script - Verify_cpu.bash         -   0.74

為了對齊最後一個欄位,應該使用 $var 進行哪些其他更改

進行預循環以計算最長的文件名,然後將其用作間距參數:

longest=0
for file in *.bash
do
 [ "${#file}" -gt "$longest" ] && longest=${#file}
done

# ... for your execution loop
printf "running the script - %${longest}s\t- "
printf "%s\n" "$var"

我假設您的所有腳本都包含在萬用字元中*.bash;根據需要進行調整。初始循環計算所需的寬度;初始printf使用該變數為for循環的每次迭代設置腳本欄位的寬度。

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