11

我有一个像下面这样的变量。

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" ]]; '

谁能指出我,我在这里缺少什么?

4

4 回答 4

25
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

祝你好运 ;)

于 2013-02-27T18:11:32.197 回答
11

在指示点将其与您的版本进行比较:

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

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

您不能在赋值中的 = 周围放置空格,并且您需要引用包含空格的字符串文字。你不需要尾随 ; 如果你打算把 then 放在它自己的线上。if-then 以“fi”而不是“if”结尾。

于 2013-02-27T18:57:44.653 回答
2

这是您的 if 语句的正确构造

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi
于 2013-02-27T18:23:25.633 回答
-1

我尝试过以下代码,它们总是以真或假返回相同的结果

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi
于 2016-03-31T09:33:23.737 回答