如何在bash shell脚本变量中查找子字符串

Bob*_*oby 10 bash shell

我有一个如下变量.

variable = This script is not found

if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if
Run Code Online (Sandbox Code Playgroud)

执行即时通讯低于错误,

line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '
Run Code Online (Sandbox Code Playgroud)

谁能指出我,我在这里失踪了什么?

Que*_*rez 23

LIST="some string with a substring you want to match"
SOURCE="substring"

if echo "$LIST" | grep -q "$SOURCE"; then
    echo "matched";
else
    echo "no match";
fi
Run Code Online (Sandbox Code Playgroud)

祝好运 ;)


Wil*_*iam 10

在指定点与您的版本进行比较:

variable="This script is not found"  # <--

if [[ "$variable" =~ "not found" ]]  # <--
then
    echo "Not Found"
else
    echo "Its there"
fi  # <--
Run Code Online (Sandbox Code Playgroud)

你不能在赋值中放置=的空格,并且你需要引用一个包含空格的字符串文字.你不需要尾随; 如果你打算把它放在自己的路上.然后if-then以"fi"而不是"if"结束.