Przemek
Przemek

Reputation: 103

Can't get bash regular expression work

This is part of my script:

   if [[ `hostname --fqdn` != '(\S+-laptop)' ]]; then
            echo "Wrong node, run it on server"
            exit 1
    fi

    echo "testing ok"
    exit 0

this is result:

++ hostname --fqdn
+ [[ mylinux1-laptop != \(\\\S\+\-\l\a\p\t\o\p\) ]]
+ echo 'Wrong node, run it on server'
Wrong node, run it on server
+ exit 1

I tested it on online tools and worked - can't figure why not in shell...

Thanks for help.

Upvotes: 1

Views: 92

Answers (1)

anubhava
anubhava

Reputation: 784898

Correct BASH regex syntax is:

[[ ! "$(hostname --fqdn)" =~ [^[:space:]]+-laptop ]] && echo "Wrong node!" && exit 1
  • regex in BASH don't require quotes around them
  • \S doesn't work on BASH regex engine
  • Use [^[:space:]] to match anything but whitespace
  • BASH regex operator is =~
  • Negation should be at the start of the condition

You can also use shell glob instead of regex:

[[ "$(hostname --fqdn)" != [^\ ]*"-laptop" ]]

Upvotes: 1

Related Questions