如何编写类似于 init.d 中使用的 bash 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2494902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write a bash script like the ones used in init.d?
提问by Neuquino
I have to write a bash script that makes lot of things. I'd like to print messages as nice as init scripts do. For example:
我必须编写一个可以制作很多东西的 bash 脚本。我想像 init 脚本一样打印消息。例如:
Doing A... [OK]
Doing B... [ERROR]
....
Do you know any way to make this?
你知道有什么方法可以做到这一点吗?
Thanks in advance
提前致谢
回答by R Samuel Klatchko
On all my Linux boxes, the code to do that is in the file:
在我所有的 Linux 机器上,执行此操作的代码都在文件中:
/etc/init.d/functions
If you include that file (. /etc/init.d/functions) and then run your code doing this:
如果您包含该文件 ( . /etc/init.d/functions) 然后运行您的代码,请执行以下操作:
action /path/to/prog args
you will get the functionality you want.
你会得到你想要的功能。
回答by Paul Tomblin
The /etc/init.d/*scripts follow a fairly easy to use template. Just find one and copy and modify it.
这些/etc/init.d/*脚本遵循一个相当容易使用的模板。只需找到一个并复制和修改它。
The [OK]/ [ERROR]stuff is done by sourcing the file /etc/init.d/functionswithin your script (at the top generally).
该[OK]/[ERROR]东西是由采购文件进行/etc/init.d/functions脚本中(通常在顶部)。
回答by SDGuero
use printf. I like having things color coded too. :)
使用printf。我也喜欢对事物进行颜色编码。:)
Here's the preamble I use in my scripts to setup the colors and a few printf statements...
这是我在脚本中用来设置颜色和一些 printf 语句的序言......
#!/bin/bash
# checkload.sh - script to check logs for errors.
#
# Created by Ryan Bray, [email protected]
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
And then I have statements like this that use colors in the output:
然后我有这样的语句,在输出中使用颜色:
printf "Checking for descrepancies in $LOAD_DATE$ADD_COMP\n"
DELTAS=$(awk 'BEGIN { FS = "\"" } {print ,,}' $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
Hope this helps!
希望这可以帮助!
-Ryan
-瑞安

