Matching regex in bash

I am trying to match bash script parameters with regex

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

I use this expression:

 regex = ^(-l)?(\ss\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 debuggex.com tests (see image but it does not work in my script

enter link description here

+4
source share
3 answers

You have problems with bash, not a regex problem.

When assigning variables in bash: there is no space around = , please. Then, if you want to keep the backslash and spaces in the regex, use single quotes around it, otherwise bash eats them for breakfast. You do not need to quote cool. And close if with fi .

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

Or use a simpler form of conditional expression:

 [[ $@ =~ $regex ]] && echo cool 
+4
source

Some versions of bash will not catch \s way we are used to in other languages ​​/ flavors. One version that it doesn't catch \s is on my MacBook Air with GNU bash, version 3.2.48(1)-release-(x86_64-apple-darwin12) .

And when creating the value of a variable, there should be no spaces around = .

As Ken-YN also has some problems in the comments on your post, I fixed it in my code below.

This should do it if the problem is \s :

 #!/bin/bash re='^(-l\ )?(-s\ [0-9]+\ )?([a-zA-Z0-9]+)(\ [a-zA-Z0-9]+)?$' if [[ $@ =~ $re ]]; then echo 'cool' fi 

No need to avoid spaces like me, but it’s easier for me to read this way.

+3
source

According to your input, it will match

 if [[ $@ =~ -l\ -s\ [0-9]+\ [a-zA-Z]+ ]] then echo 'cool' else echo 'check again' fi 
0
source

Source: https://habr.com/ru/post/1501996/


All Articles