我需要编写一个bash脚本来完成很多任务。我想要像init脚本一样打印漂亮的消息。例如:
Doing A... [OK]
Doing B... [ERROR]
....
你知道有什么方法可以做到这一点吗?
提前致谢。
在我所有的Linux机器上,完成这个任务的代码都在这个文件中:
/etc/init.d/functions
如果您包含那个文件(. /etc/init.d/functions
)并运行以下代码:action /path/to/prog args
你将获得所需的功能。
/etc/init.d/*
脚本遵循一个相当易于使用的模板。只需找到一个并复制和修改它。
[OK]
/[ERROR]
的内容是通过在脚本中引用文件/etc/init.d/functions
(通常在顶部)来完成的。
使用printf。我也喜欢有颜色编码的东西。 :)
以下是我在脚本中使用的引言,用于设置颜色和一些printf语句...
#!/bin/bash
# checkload.sh - script to check logs for errors.
#
# Created by Ryan Bray, rbray@xxx.com
set -e
# Text color variables
txtund=$(tput sgr 0 1) # Underline
txtbld=$(tput bold) # Bold
txtred=$(tput setaf 1) # Red
txtgrn=$(tput setaf 2) # Green
txtylw=$(tput setaf 3) # Yellow
txtblu=$(tput setaf 4) # Blue
txtpur=$(tput setaf 5) # Purple
txtcyn=$(tput setaf 6) # Cyan
txtwht=$(tput setaf 7) # White
txtrst=$(tput sgr0) # Text reset
然后我有这样的语句,它们在输出中使用颜色:
printf "Checking for descrepancies in $LOAD_DATE$ADD_COMP\n"
DELTAS=$(awk 'BEGIN { FS = "\"" } {print $24,$26,$28}' $COMP_FILE)
if [[ "$DELTAS" == *[1-9]* ]]; then
printf "%74s[${txtred}FAIL${txtrst}]\n"
printf "$COMP_FILE contains descrepancies.\n"
exit 1
else
printf "%74s[${txtgrn}PASS${txtrst}]\n"
fi
/etc/init.d/*
中查看文件,这些文件似乎以相同的方式使用/lib/lsb/init-functions
,调用其定义的函数,例如log_begin_msg、log_progress_msg、log_warning_msg、log_failure_msg和log_end_msg。其中一个还引用了“/etc/init.d/functions”,但只有系统是Redhat时才会这样做。 - 13ren