[[测试块]内的Bash模式匹配

时间:2016-06-07 17:52:43

标签: regex bash shell pattern-matching

我正在编写一个可以在多台机器上执行相同任务的脚本,如下所示:

#!/bin/bash
if [[ hostname = login.machine1 ]]; then
    #do things how they are done on machine1
    ...
elif [[ hostname = login.machine2 ]]; then
    #etc.
fi

问题:某些计算机有多个登录节点,例如login1.machine2login2.machine2等。我尝试过shell模式匹配和正则表达式,但它们都不起作用:

if [[ hostname = login?.machine2 ]]
if [[ hostname == login?.machine2 ]]
if [[ hostname =~ login[0-9].machine2 ]]
if [[ hostname =~ login[0-9]\.machine2 ]]

和至少十几个类似的模式,有或没有引号等。如果hostname = login1.machine2或login2.machine2等,那么使测试返回true的正确方法是什么?对于与[而非[[一起使用的内容的加分点。

3 个答案:

答案 0 :(得分:3)

您需要$ before before hostname才能使用该变量。

if [[ $hostname =~ login[0-9]\.machine2 ]]; then
   echo "ok"
fi

对于单[(sh),在bash上添加了正则表达式运算符=~,所以不应该用sh本地执行它。

答案 1 :(得分:0)

[[ hostname =~ ... ]]是否应该调用命令hostname,还是有一个名为hostname的变量?使用$HOSTNAME或命令替换$(hostname)

如果担心可移植性,可以使用AWK,旧学校命令替换:

if printf "%s\n" "`hostname`" | awk '!/login[[:digit:]]\.machine2/{exit 1}'; then
  printf "Matches...\n"
else
  printf "Doesn't match\n"
fi 

如果不是,我强烈推荐the answer by naab

答案 2 :(得分:0)

命令if [[ $(hostname) = login?.machine2 ]] 需要包装:

   If itemIndex > -1 Then
                  Dim item As Object = ListBox2.Items(itemIndex) 'get the item at that index.
        Dim s As String = ListBox2.GetItemText(item) 'get the text displayed
        Dim g As Graphics = Me.ListBox2.CreateGraphics()

        If g.MeasureString(s, Me.ListBox2.Font).Width > Me.ListBox2.ClientRectangle.Width Then
            Me.ToolTip1.SetToolTip(Me.ListBox2, s)
        Else
            Me.ToolTip1.SetToolTip(Me.ListBox2, "")
        End If
        g.Dispose()
    End If