1

我不明白他在这里犯了什么错误,因为我是 shell 脚本的新手。请帮我

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

5 回答 5

3

您需要在您的病情周围留出空间:

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

1) 如果您使用的是 bash,则可以使用内置命令[[ ..]]代替test( [ ...]) 命令。

2)您也可以wc通过使用-cgrep 选项来避免。

if [[ $(grep -c -o BPR $file) == 1 ]]; then
于 2013-10-07T17:28:16.070 回答
3

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

if [ $(grep -o BPR $file | wc -l) == 1 ]; then
于 2013-10-07T17:27:59.610 回答
1

有几件事:

  • [您需要在和周围留出空格]
  • 您可能不想使用[and ]

if语句运行您给它的命令。如果命令返回零,则执行该then部分if语句。如果命令返回非零,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!

同样,第一行是您的输出ls。由于该文件存在且是可声明的,因此ls返回一个0. 这导致if子句执行,打印第二行。

如果我想测试一个文件是否存在怎么办?

您可以使用测试命令:

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

如果文件foo存在,则测试命令返回 0。这意味着echo "Hey, the file exists!"将执行。如果文件不存在,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测试命令是否成功,并且实际上并没有进行布尔检查(例外情况是,如果您使用双方括号,例如[[and]] 而不是[and ]。这些是内置在 shell 中的,而不是作为内置命令。)

您可能想要做的是:

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

旗帜-q告诉grep关闭它的yap。如果您给它的模式在文件中,该grep命令将返回 a 0,如果不能,则返回非零(确切值无关紧要 - 只要它不是 0)。

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

于 2013-10-07T19:59:15.527 回答
1

除了语法错误之外,wc如果您不在乎BPR文件中可能出现多次,则不需要:

if grep -o BPR "$file"; then
于 2013-10-07T17:46:00.147 回答
0

如果您只需要知道字符串是否匹配而不显示实际匹配使用

if grep -q 'anystring' file ; then
于 2013-10-07T17:50:46.483 回答