bash:在窗口的右端回显一些东西(右对齐)

Sto*_*oic 9 bash

我正在寻找生成成功/失败消息,这些消息在bash中是正确的.一个例子是apache2在执行时产生的内容:sudo /etc/init.d/apache2 reload等等

在上面的例子中,apache2产生非常好的和简洁的[OK]或者[fail]右对齐的消息.

此外,我们很想知道如何让文字变红,以防万一我们要发[fail]短信.

Sie*_*geX 9

#!/bin/bash

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)

col=80 # change this to whatever column you want the output to start at

if <some condition here>; then
  printf '%s%*s%s' "$GREEN" $col "[OK]" "$NORMAL"
else
  printf '%s%*s%s' "$RED" $col "[FAIL]" "$NORMAL"
fi
Run Code Online (Sandbox Code Playgroud)

  • @SiegeX:`col = $(tput cols)`比硬编码更好,更符合其他`tput`用途.此外,您的方法为颜色转义占用了额外的空间,实际上并没有占用任何空间.`printf'%s%*s%s'"$ GREEN"$ col'[OK]'"$ NORMAL"`可能更干净. (2认同)