I've recently been practicing both with regexes and shell scripting. I guess just to gain basic literacy. I've tried to match an input value to a regex to assess whether to continue with the script. However I feel I've had to write too much code to make it happen because the simple way, for some reason, wouldn't cut it for me.
The regex is designed to match a 4 or 5 digit string. The regex itself works, it is not the issue. (except if its syntax has to be changed in the conditional)
This was the easy method I've tried. I've tried different ways of regex notation and brackets and quotation marks. (something with single brackets being Posix/requirin brackets?)
Assume that I've run the code with 'foo 4535'
if [[ $1 =~ '^\b\d{4}\b|\b\d{5}\b$' ]]; then
echo "foo matches regex"
fi
so my main question is; How do I get this short version to work?
I have looked at similar questions and I came to a work around as such:
foo=$1
echo $foo | grep -P -q '^\b\d{4}\b|\b\d{5}\b$'
bar=$?
if [[ $bar != '0' ]]; then
echo "foo matches regex"
fi
And this works. Which is fine. But there are a few things in there that I don't understand on which I might like some clarity (solely for the purpose of exploratory learning ;) ), so feel free to ignore
When I tried reducing the first section by replacing it with
foo=$(echo "$bar" | grep -P -q '^\b\d{4}\b|\b\d{5}\b$')
echo $foo
It would give me an empty line, indicating that $foo is empty/falsy? Only when passing it through $? (of which I don't understand what kind of variable this is, how can I google for such concepts?) I get a value (which is represented as 0 or 1 when echoing, I am unsure whether this is a string or a boolean), Why is this?
And second of all, why would the input matching the regex give me 0, and not matching give me 1? isn't this counterintuitive? What kind of value is this?
My apologies if I haven't asked/formatted this question to style. I am not experienced with asking questions in a Stack overflow Format.
If you have any suggestions on how to learn more about shell scripting I would love to hear it!
Thank you very much!