Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file contains a specific string using Bash

Tags:

grep

bash

shell

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?

like image 762
Hakim Avatar asked Jul 02 '12 04:07

Hakim


People also ask

How do I search for a specific string in a file in Linux?

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 .

How to check if a string exists in a bash file?

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.

How do I check if a file is empty in Bash?

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 [..]

How do I check for substrings in Bash shell?

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:

What is the command to check if a file exists?

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...


1 Answers

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 [[]].

like image 172
Igor Chubin Avatar answered Oct 06 '22 21:10

Igor Chubin