shell脚本错误我不明白他在这里的错误,因为我是新的shell脚本。请帮我如果条件
./bpr: line 8: syntax error near unexpected token `then'
./bpr: line 8: ` if[$(grep -o BPR $file | wc -l) == 1]; then '
shell脚本错误我不明白他在这里的错误,因为我是新的shell脚本。请帮我如果条件
./bpr: line 8: syntax error near unexpected token `then'
./bpr: line 8: ` if[$(grep -o BPR $file | wc -l) == 1]; then '
您需要之间加空格您[
]
,试试这个:
if [ $(grep -o BPR $file | wc -l) == 1 ]; then
你需要在你的条件的空间:
if [ $(grep -o BPR $file | wc -l) == 1 ]; then
^ ^
1)如果你是使用bash,你可以使用内置的[[ ..]]
而不是test
([ ...]
)命令。
2)您也可以用grep的-c
选项避免wc
。
if [[ $(grep -c -o BPR $file) == 1 ]]; then
除此之外,你不需要wc
或者,如果你不小心可能存在的BPR
多个occurrances文件中:
if grep -o BPR "$file"; then
你不需要wc任何一种方式:'grep -c -o BPR' –
我依靠退出代码来区分“不匹配”和“至少一个匹配”。使用'-c',如果有一个有效的区别,例如1个匹配和2个,你仍然需要捕获值并进行比较。 – chepner
,如果你只需要知道如果字符串没有显示实际比赛使用
if grep -q 'anystring' file ; then
几件事情相匹配:
[
和]
附近的空格。[
和]
。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子句。
您需要在if后添加空格。 –
是的。只是努力与编辑选项;-)仍然不知道如何格式化最后一行类似于我的答案的第一行:D –
为您的良好使用grep :)。 –