I have to write a small bash script that determines if a string is valid for the bash variable naming rules. My script accepts the variable name as an argument. I am trying to pass that argument to the grep command with my regex but everything I tried, grep tries to open the value passed as a file.
I tried placing it after the command as such
grep "$regex" "$1"
and also tried passing it as redirected input, both with and without quotes
grep "$regex" <"$1"
and both times grep tries to open it as a file. Is there a way to pass a variable to the grep command?
Both your examples interpret "$1" as a filename. To use a string, you can use
echo "$1" | grep "$regex"
or a bash specific "here string"
grep "$regex" <<< "$1"
You can also do it faster without grep with
[[ $1 =~ $regex ]] # regex syntax may not be the same as grep's
or if you're just checking for a substring,
[[ $1 == *someword* ]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With