Reputation: 91
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
Upvotes: 4
Views: 293
Reputation: 1882
Some versions of bash does not catch \s
the way we are used to in other languages/flavors.
One version it does not catch \s
is on my MacBook Air with GNU bash, version 3.2.48(1)-release-(x86_64-apple-darwin12)
.
And you should not have spaces around =
when assigning a value to a variable.
As Ken-Y-N said in the comments to your post, your pattern has some problems as well, I fixed it in my code below.
This should do it if \s
is the problem:
#!/bin/bash
re='^(-l\ )?(-s\ [0-9]+\ )?([a-zA-Z0-9]+)(\ [a-zA-Z0-9]+)?$'
if [[ $@ =~ $re ]]; then
echo 'cool'
fi
There's no need to escape the spaces like i did, but I find it easier to read this way.
Upvotes: 3
Reputation: 12629
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
Upvotes: 4
Reputation: 1420
As per your input, this will match
if [[ $@ =~ -l\ -s\ [0-9]+\ [a-zA-Z]+ ]]
then
echo 'cool'
else
echo 'check again'
fi
Upvotes: 0