将搜索字符串作为shell变量传递给grep

use*_*073 4 bash grep

我必须编写一个小的bash脚本来确定字符串是否对bash变量命名规则有效.我的脚本接受变量名作为参数.我试图用我的正则表达式将该参数传递给grep命令,但我尝试了一切,grep尝试打开作为文件传递的值.

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"
Run Code Online (Sandbox Code Playgroud)

并且两次grep都试图将其作为文件打开.有没有办法将变量传递给grep命令?

tha*_*guy 7

您的示例都将"$ 1"解释为文件名.要使用字符串,您可以使用

echo "$1" | grep "$regex" 
Run Code Online (Sandbox Code Playgroud)

或bash特定的"here string"

grep "$regex" <<< "$1"
Run Code Online (Sandbox Code Playgroud)

你也可以在没有grep的情况下更快地完成它

[[ $1 =~ $regex ]]  # regex syntax may not be the same as grep's
Run Code Online (Sandbox Code Playgroud)

或者如果您只是检查子字符串,

[[ $1 == *someword* ]]
Run Code Online (Sandbox Code Playgroud)