Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching regex in bash

Tags:

regex

bash

I'm trying to match the parameters of a bash script with a regex

mykill.bash [-l] [-s SIGNO] pattern1 pattern2

I'm using this expression:

regex = ^(-l)?(\s-s\s[0-9]+)?(\s[a-zA-Z0-9]+){1,2}$ <br>
if [[ $@ =~ $regex ]]; then echo 'cool'

for example ./mykill.bash -l -s 33 abc gives $@='-l -s 33 abc' which passes the debuggex.com tests (see image but it doesn't work in my script

enter link description here

like image 845
user34345352 Avatar asked Mar 22 '23 10:03

user34345352


1 Answers

You have bash problems, not a regex problem.

When assigning variables in bash: no space around the = please. Then if you want to preserve backslashes and whitespace in the regex, use single quotes around it, otherwise bash eats them for breakfast. You don't need to quote cool. And close the if with a fi.

regex='^(-l)?(\s-s\s[0-9]+)?(\s[a-zA-Z0-9]+){1,2}$ <br>'
if [[ $@ =~ $regex ]]; then echo cool; fi

Or use the simpler form of the conditional:

[[ $@ =~ $regex ]] && echo cool
like image 81
SzG Avatar answered Apr 02 '23 20:04

SzG