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

12

我有一个如下的变量。

variable = This script is not found

if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if

在执行时出现以下错误,
line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '

有人能指出我在这里缺少什么吗?


2
在“=”和“”之间不应该有空格。请写成“=”。 - Explosion Pills
之前尝试过,但是出现了其他错误。第4行:需要条件二进制运算符./test.sh: 第4行:=附近有语法错误./test.sh: 第4行:`if [[ "$variable" = "not found" ]]; ' - Boby
1
如果你将顶部的赋值改为 variable="This script is not found",会发生什么?祝好运。 - shellter
5个回答

28
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

祝你好运 ;)


11

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

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

if [[ "$variable" =~ "not found" ]]  # <--
then
    echo "Not Found"
else
    echo "Its there"
fi  # <--

在赋值语句中,等号两边不能有空格,并且如果字符串字面量中包含空格,则需要将其用引号括起来。如果if语句后面是单独一行的then,就不需要分号。而if-then语句以"fi"结尾,而不是"if"。


2
这是您的if语句的正确构建方式。
if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi

0

输入:

line="There\'s a substring to be found!"

if [[ "$line" =~ *"substring"* ]]; then
    echo "Not Found";
else
    echo "Found!"
fi

输出:

Found!

-1

我已经尝试了以下代码,但始终返回相同的结果,无论是true还是false

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接