2012-05-27 33 views
3

在“RabbitMQ的-ENV”的RabbitMQ的脚本文件,有下面几行HOSTNAME的使用。关于RabbitMQ的的bash脚本

[ "x" = "x$HOSTNAME" ] && HOSTNAME=`env hostname` 
[email protected]${HOSTNAME%%.*} 

第一行是什么意思?是否检查$HOSTNAME是否设置,如果没有设置,设置为'env hostname'

它是占据另一个相关的脚本文件"rabbitmq-server"的大部分一线的编程模式。所以我想知道这一行的清晰含义。

对于第二行,有什么的HOSTNAME%%.*意思?

回答

6

这个表达式检查HOSTNAME是取消设置:

[ "x" = "x$HOSTNAME" ] 

如果HOSTNAME没有设置,这最终看起来像:

[ "x" = "x" ] 

这当然计算结果为true。表达式:

[ "x" = "x$HOSTNAME" ] && HOSTNAME=`env hostname` 

可否设定HOSTNAME到的env hostname输出,如果&&之前的表达是true。调用env hostname与仅调用hostname完全相同,后者仅输出本地主机的名称。

第二个表达式:

[email protected]${HOSTNAME%%.*} 

是使用bash变量扩展以剥离一切,但主机名的第一组分。给定HOSTNAME="host.example.com",${HOSTNAME%%.*}返回host。你可以阅读更多的人bash页:

${parameter%%word} 
    Remove matching suffix pattern. The word is expanded to produce 
    a pattern just as in pathname expansion. If the pattern matches 
    a trailing portion of the expanded value of parameter, then 
    the result of the expansion is the expanded value of parameter 
    with the shortest matching pattern (the ``%'' case) or the longest 
    matching pattern (the ``%%'' case) deleted. 

所以这台NODENAME[email protected],假设你的本地主机名是host.example.com

+0

非常感谢。 –

+1

@ChenYu:脚本中显示的表单很古老。测试空或未设置变量的正确方法是Bash中的'[[-z $ HOSTNAME]]'或不支持双括号的Bourne shell中的'[-z“$ HOSTNAME”]'''。单支架形式也适用于Bash。 (答案+1) –