This question already has an answer here:
I didnt understand what he error here as iam new to shell scripting. Please help me
./bpr: line 8: syntax error near unexpected token `then'
./bpr: line 8: ` if[$(grep -o BPR $file | wc -l) == 1]; then '
Aside from your syntax errors, you don't need
wc
either if you don't care that there may be multiple occurrances ofBPR
in the file:A couple of things:
[
and]
.[
and]
.The
if
statement runs the command you give it. If the command returns a zero, thethen
portion of theif
statement is executed. If the command returns a non-zero, theelse
portion (if it exists) is executed.Try this:
You'll get an output:
That first statement, of course is the output of your
ls
command. The second one is the output from theif
statement. Thels
ran, but couldn't access that file (it doesn't exist) and returned e1
. That caused theelse
clause to execute.Try this:
You'll get an output:
Again the first line is your output from
ls
. Since the file exists, and is statable,ls
returned a0
. This caused theif
clause to execute, printing the second line.What if I want to test whether or not a file exists?
You can use the test command:
If the file
foo
exists, the test command returns a 0. That means theecho "Hey, the file exists!"
will execute. If the file doesn't exist, test will return a 1, and theelse
clause will execute.Now do this:
That first number is the
inode
. If two matching files have the same inode, they are hard linked to each other. The[
...]
are merely another name for thetest
command. The[
is an actual command. That's why you need spaces around it. You also see thatif
tests whether or not a command succeeds, and doesn't really do boolean checking (the exception is if you use double square brackets like[[
and]]
instead of[
and]
. These are built into the shell and not as builtin commands.)What you probably want to do is:
The
-q
flag tellsgrep
to shut its yap. Thegrep
command will return a0
if the pattern you give it is in the file, and a non-zero (exact value doesn't matter -- as long as it isn't 0) if it can't.Note I don't need
[
...]
because I am using the output of the grep command to see if I should execute the if clause of that statement.You need to add spaces between your
[
]
, try this:You need a space around your condition:
1) If you are using bash, you can use the built-in
[[ ..]]
instead oftest
([ ...]
) command.2) You can also avoid
wc
by using-c
option of grep.if you only need to know if the string matches without showing the actual match use