How to use a regex in a bash conditional

Use the double bracket syntax to use regular expressions (aka regex or regexp) in bash conditionals:

me@pc ~/tmp/bashregextest $ if [[ "foo/bar" =~ ^foo ]]; then echo 'yes'; else echo 'no'; fi
yes
me@pc ~/tmp/bashregextest $ if [[ "foo/bar" =~ ^bar ]]; then echo 'yes'; else echo 'no'; fi
no

Be sure to include the spaces between the double brackets and the conditional inside, otherwise you’ll get an error like this:

me@pc ~/tmp/bashregextest $ if [[ "foo/bar" =~ ^foo]]; then echo 'yes'; else echo 'no'; fi
bash: syntax error in conditional expression: unexpected token `;'
bash: syntax error near `;'

Source: Tutorial: Conditions in bash scripting (if statements)

Last modified: 03/12/2011 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top