2013-02-27 112 views
5

我有一个像下面这样的变量。如何在bash shell脚本变量中查找子字符串

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

不应该有一个'='和'〜'间空间返回相同的结果代码。写成'=〜' – 2013-02-27 17:57:46

+0

之前已经试过。但得到了其他错误第4行:期望条件二元运算符./test.sh:第4行:语法错误附近'=〜'./test.sh:第4行:'if [[“$ variable”=〜“not found” ]]; ' – Boby 2013-02-27 17:59:29

+1

如果将顶部的assigment更改为'variable =“,则会发生什么情况此脚本未找到”'?祝你好运。 – shellter 2013-02-27 18:15:26

回答

13
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 

好运;)

2

这里是你的if语句

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

在指定的点与你的版本比较一下一个正确的结构:

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

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

你可以在作业中不要放置空格=,并且需要引用具有空格的字符串文字。你不需要尾随;如果你打算把它放在自己的路线上。而if-then以“fi”而不是“if”结尾。

0

我曾尝试下面总是无论是真或假

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