2013-10-07 51 views
1

shell脚本错误我不明白他在这里的错误,因为我是新的shell脚本。请帮我如果条件

./bpr: line 8: syntax error near unexpected token `then' 
./bpr: line 8: ` if[$(grep -o BPR $file | wc -l) == 1]; then ' 

回答

3

您需要之间加空格您[],试试这个:

if [ $(grep -o BPR $file | wc -l) == 1 ]; then 
3

你需要在你的条件的空间:

if [ $(grep -o BPR $file | wc -l) == 1 ]; then 
    ^        ^

1)如果你是使用bash,你可以使用内置的[[ ..]]而不是test[ ...])命令。

2)您也可以用grep的-c选项避免wc

if [[ $(grep -c -o BPR $file) == 1 ]]; then 
+0

您需要在if后添加空格。 –

+0

是的。只是努力与编辑选项;-)仍然不知道如何格式化最后一行类似于我的答案的第一行:D –

+0

为您的良好使用grep :)。 –

1
从您句法错误

除此之外,你不需要wc或者,如果你不小心可能存在的BPR多个occurrances文件中:

if grep -o BPR "$file"; then 
+1

你不需要wc任何一种方式:'grep -c -o BPR' –

+0

我依靠退出代码来区分“不匹配”和“至少一个匹配”。使用'-c',如果有一个有效的区别,例如1个匹配和2个,你仍然需要捕获值并进行比较。 – chepner

0

,如果你只需要知道如果字符串没有显示实际比赛使用

if grep -q 'anystring' file ; then 
1

几件事情相匹配:

  • 您需要[]附近的空格。
  • 你可能不希望使用[]

if语句运行您给它的命令。如果该命令返回零,则会执行if语句的then部分。如果该命令返回非零值,则执行else部分(如果存在)。

试试这个:

$ if ls some.file.name.that.does.not.exist 
> then 
>  echo "Hey, the file exists!" 
> else 
>  echo "Nope. File isn't there" 
> fi 

你会得到一个输出:

ls: some.file.name.that.does.not.exist: No such file or directory 
Nope. File isn't there 

,首先声明,当然是你的ls命令的输出。第二个是if声明的输出。 ls运行,但无法访问该文件(它不存在)并返回e 1。这导致else子句执行。

试试这个:

$ touch foo 
$ if ls foo 
>  echo "Hey, the file exists!" 
> else 
>  echo "Nope. File isn't there" 
> fi 

你会得到一个输出:

foo 
Hey, the file exists! 

第1线路是从ls你的输出。由于该文件存在并且是可以统计的,所以ls返回0。这导致if子句执行,打印第二行。

如果我想测试如果文件是否存在?如果foo存在该文件,测试命令返回一个0。这意味着echo "Hey, the file exists!"将执行

$ if test -e foo 
> then 
>  echo "Hey, the file exists!" 
> else 
>  echo "Nope. File isn't there" 
> fi 

可以使用test命令。如果文件不存在,测试将返回1,并且else子句将执行。

现在做到这一点:

$ ls -il /bin/test /bin/[ 
10958 -rwxr-xr-x 2 root wheel 18576 May 28 22:27 /bin/[ 
10958 -rwxr-xr-x 2 root wheel 18576 May 28 22:27 /bin/test 

这第一个号是inode。如果两个匹配的文件具有相同的inode,则它们彼此难以链接。 [ ... ]只是test命令的另一个名称。 [是一个实际的命令。这就是为什么你需要它周围的空间。您还会看到if测试命令是否成功,并且没有真正执行布尔检查(例外情况是,如果使用双方括号,例如[[]]而不是[]。这些内置于外壳中,而不是。内置命令)

你可能想要做的是:

if grep -q "BPR" "$file" 
then 
    echo "'BPR' is in '$file'" 
fi 

-q标志告诉grep关闭其邑。如果您给出的模式在文件中,则grep命令将返回0,如果不能,则返回非零值(确切的值不重要 - 只要不是0)。

注意我不需要[ ... ],因为我正在使用grep命令的输出来查看是否应该执行该语句的if子句。