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?
If you have a file opened in nano and need to find a particular string, there's no need to exit the file and use grep on it. Just press Ctrl + W on your keyboard, type the search string, and hit Enter .
Fixed now.) A couple of notes for folks looking at this answer: 1) In bash, 0 is always true and anything else is always false 2) Only use the -x flag if you want the entire line to match exactly. If you just want to find if your string exists in the file at all, leave that off.
Bash/Shell: Check if file exists (is empty or not empty) To check if the file exists and if it is empty or if it has some content then we use " -s " attribute Check if file exists and empty or not empty using double brackets [ [..]] Check if file exists and empty or not empty using double brackets [..]
There are more than one way to check for substrings in bash shell. I'll show some simple examples first, followed by a cool bash script that uses this concept in a real-world scenario. If you are familiar with the conditional statements in bash, you can use it to check if a string contains the substring in the following manner:
1 -b FILE - True if the FILE exists and is a special block file. 2 -c FILE - True if the FILE exists and is a special character file. 3 -d FILE - True if the FILE exists and is a directory. 4 -e FILE - True if the FILE exists and is a file, regardless of type (node, directory, socket, etc.). More items...
if grep -q SomeString "$File"; then Some Actions # SomeString was found fi
You don't need [[ ]]
here. Just run the command directly. Add -q
option when you don't need the string displayed when it was found.
The grep
command returns 0 or 1 in the exit code depending on the result of search. 0 if something was found; 1 otherwise.
$ echo hello | grep hi ; echo $? 1 $ echo hello | grep he ; echo $? hello 0 $ echo hello | grep -q he ; echo $? 0
You can specify commands as an condition of if
. If the command returns 0 in its exitcode that means that the condition is true; otherwise false.
$ if /bin/true; then echo that is true; fi that is true $ if /bin/false; then echo that is true; fi $
As you can see you run here the programs directly. No additional []
or [[]]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With