I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
What's wrong in my code?
I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
What's wrong in my code?
In case you want to checkif the string matches the whole line and if it is a fixed string, You can do it this way
example
From the man file:
In addition to other answers, which told you how to do what you wanted, I try to explain what was wrong (which is what you wanted.
In Bash,
if
is to be followed with a command. If the exit code of this command is equal to 0, then thethen
part is executed, else theelse
part if any is executed.You can do that with any command as explained in other answers:
if /bin/true; then ...; fi
[[
is an internal bash command dedicated to some tests, like file existence, variable comparisons. Similarly[
is an external command (it is located typically in/usr/bin/[
) that performs roughly the same tests but needs]
as a final argument, which is why]
must be padded with a space on the left, which is not the case with]]
.Here you needn't
[[
nor[
.Another thing is the way you quote things. In bash, there is only one case where pairs of quotes do nest, it is
"$(command "argument")"
. But in'grep 'SomeString' $File'
you have only one word, because'grep '
is a quoted unit, which is concatenated withSomeString
and then again concatenated with' $File'
. The variable$File
is not even replaced with its value because of the use of single quotes. The proper way to do that isgrep 'SomeString' "$File"
.The exit status is 0 (true) if the pattern was found;
I done this, seems to work fine
Example
Try this: