我正在寻找生成成功/失败消息,这些消息在bash中是正确对齐的。一个例子是apache2在执行时产生的内容:sudo /etc/init.d/apache2 reload
等。
在上面的示例中,apache2生成非常简洁的[OK]
或[fail]
消息,这些消息是正确对齐的。
此外,我们很想知道如何将文字设为红色,以防我们发出[fail]
消息。
答案 0 :(得分: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
答案 1 :(得分: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
导致: (注:法语区域;-))
希望它会有所帮助!
答案 2 :(得分:0)
这主要是基于centos&#39;功能&#39;脚本,但更多的剥离
#!/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
"$@" && echo_success $"$STRING" || echo_failure $"$STRING"
rc=$?
echo
return $rc
}
action testing true
action testing false