2011-03-31 70 views
8

我正在寻找生成在bash中右对齐的成功/失败消息。一个例子是apache2在执行时产生的内容:sudo /etc/init.d/apache2 reloadbash:在窗口右端回显一些东西(右对齐)

在上面的例子中,apache2产生非常好和简洁的[OK][fail]消息,它们是右对齐的。

另外,很想知道如何获得文本红色,以防万一,我们要产生一个[fail]消息。

+1

用printf;参见http://stackoverflow.com/questions/2199843/bourne-shell-left-right-justify – 2011-03-31 20:55:59

回答

7
#!/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 
+2

@SiegeX:'col = $(tput cols)'比硬编码要好,并且与其他'tput'用途更一致。此外,您的方法为颜色转义消耗额外的空间,实际上并不占用任何空间。 'printf'%s%* s%s'“$ GREEN”$ col'[OK]'“$ NORMAL”'可能更干净。 – geekosaur 2011-03-31 20:59:51

+0

@geek:我决定不用'输入cols'和'输入cup',因为前者不给你指定列的灵活性(它可能不是最好的毛边),后者需要#行。 – SiegeX 2011-03-31 21:04:41

+1

@SiegeX:你可以使用'tput hpa'作为后者。 – geekosaur 2011-03-31 21:07:14

2

看一看这个线程,可能是有趣:how to write a bash script like the ones used in init.d?

在Linux CentOS的6.5,我使用的/etc/init.d/functions文件:

#!/bin/bash 
. /etc/init.d/functions # include the said file 

action "Description of the action" command 

exit 0 

假设command成功返回0,如果发生错误,则返回正值。 为了让脚本易于阅读,我使用了函数调用而不是整个命令。

下面是一个例子:

#!/bin/bash 

. /etc/init.d/functions 

this_will_fail() 
{ 
    # Do some operations... 
    return 1 
} 

this_will_succeed() 
{ 
    # Do other operations... 
    return 0 
} 


action "This will fail"  this_will_fail 
action "This will succeed" this_will_succeed 

exit 0 

导致: console output (注:法语的语言环境;-))

希望对大家有所帮助!

+1

请注意,'/ etc/init.d/functions'的导入修改了'$ PATH'。 – epsilonhalbe 2017-03-22 10:39:25

0

这主要是基于CentOS的“功能”脚本什么的,但更精简

#!/bin/bash 

RES_COL=60 
MOVE_TO_COL="printf \\033[${RES_COL}G" 

DULL=0 
BRIGHT=1 

FG_BLACK=30 
FG_RED=31 
FG_GREEN=32 
FG_YELLOW=33 
FG_BLUE=34 
FG_MAGENTA=35 
FG_CYAN=36 
FG_WHITE=37 

ESC="^[[" 
NORMAL="${ESC}m" 
RESET="${ESC}${DULL};${FG_WHITE};${BG_NULL}m" 

BLACK="${ESC}${DULL};${FG_BLACK}m" 
RED="${ESC}${DULL};${FG_RED}m" 
GREEN="${ESC}${DULL};${FG_GREEN}m" 
YELLOW="${ESC}${DULL};${FG_YELLOW}m" 
BLUE="${ESC}${DULL};${FG_BLUE}m" 
MAGENTA="${ESC}${DULL};${FG_MAGENTA}m" 
CYAN="${ESC}${DULL};${FG_CYAN}m" 
WHITE="${ESC}${DULL};${FG_WHITE}m" 

SETCOLOR_SUCCESS=$GREEN 
SETCOLOR_FAILURE=$RED 
SETCOLOR_NORMAL=$RESET 

echo_success() { 
    $MOVE_TO_COL 
    printf "[" 
    printf $SETCOLOR_SUCCESS 
    printf $" OK " 
    printf $SETCOLOR_NORMAL 
    printf "]" 
    printf "\r" 
    return 0 
} 

echo_failure() { 
    $MOVE_TO_COL 
    printf "[" 
    printf $SETCOLOR_FAILURE 
    printf $"FAILED" 
    printf $SETCOLOR_NORMAL 
    printf "]" 
    printf "\r" 
    return 1 
} 

action() { 
    local STRING rc 

    STRING=$1 
    printf "$STRING " 
    shift 
    "[email protected]" && echo_success $"$STRING" || echo_failure $"$STRING" 
    rc=$? 
    echo 
    return $rc 
} 

action testing true 
action testing false