Linux if grep found

Can grep return true/false or are there alternative methods

As a part of this script, I need to be able to check if the first argument given matches the first word of file. If it does, exit with an error message; if it doesn’t, append the arguments to the file. I understand how to write the if statement, but not how to use grep within a script. I understand that grep will look something like this

I feel like this should be much easier than I am making it. I’m getting an error «too many arguments» on the if statement. I got rid of the space between grep -q and then got an error binary operator expected.

if [ grep -q ^$1 schemas.txt ] then echo "Schema already exists. Please try again" exit 1 else echo "$@" >> schemas.txt fi 

Lose the [ … ] and it’ll work. Though you probably want to quote your pattern: if grep -q «^$1» schemas.txt; then …

Bash oneliner. If the string «foo» is found in file content.txt then run the command work.sh, otherwise do nothing : cat content.txt | grep «foo» && work.sh

6 Answers 6

grep returns a different exit code if it found something (zero) vs. if it hasn’t found anything (non-zero). In an if statement, a zero exit code is mapped to «true» and a non-zero exit code is mapped to false. In addition, grep has a -q argument to not output the matched text (but only return the exit status code)

So, you can use grep like this:

if grep -q PATTERN file.txt; then echo found else echo not found fi 

As a quick note, when you do something like if [ -z «$var» ]… , it turns out that [ is actually a command you’re running, just like grep. On my system, it’s /usr/bin/[ . (Well, technically, your shell probably has it built-in, but that’s an optimization. It behaves as if it were a command). It works the same way, [ returns a zero exit code for true, a non-zero exit code for false. ( test is the same thing as [ , except for the closing ] )

Источник

if statement with grep [duplicate]

What I’m trying to do is the get the user input and search through the file, If it match it will show the result, else it will echo $keyword not found. But my scrip is always return fault.

 read -p "Enter keyword: " keyword if search="$(cat ./records | grep '$keyword')" then echo "$search" else echo "$keyword not found!" fi ;; 

the error is that you are using ‘$keyword’ . within single quotes the variable is not expanded and treated as text. use «$keyword» instead.

Читайте также:  Отображение всех пользователей linux

2 Answers 2

read -r -p 'Enter pattern: ' pattern result=$( grep -e "$pattern" records ) if [ -n "$result" ]; then printf '%s\n' "$result" else printf 'No match found for pattern "%s"\n' "$pattern" fi 
  • The assignment to search ( result in my code) is best done outside of the if statement.
  • Test with -n («is this string non-empty?») on the result.
  • Don’t single-quote the variable (it will prevent the shell from expanding its value). Double quote it instead.
  • Notice «pattern» rather than «keyword». The way you use grep here will use the user-supplied string as a regular expression (a pattern, such as cat.*dog ), not necessarily as a plain fixed string.
  • cat should be used to concatenate files, in most other cases it’s more or less useless.
  • Use read -r to allow the user to enter backslashes.
read -r -p 'Enter pattern: ' pattern if ! grep -e "$pattern" records; then printf 'No match found for pattern "%s"\n' "$pattern" fi 

This avoids storing a potentially huge amount of data in a shell variable and instead relies on the exit status of grep to tell whether the pattern may be found in the file or not. If the pattern is found, the matching lines will be printed (and nothing more has to be done).

Regarding the use of printf in place of echo : Why is printf better than echo?

Shorter, using a short-circuit OR.

read -r -p 'Enter pattern: ' grep -e "$REPLY" records || printf 'No match found for pattern "%s"\n' "$REPLY" 

Источник

How can I check if ‘grep’ doesn’t have any output?

I need to check if the recipient username is in file /etc/passwd which contains all the users in my class, but I have tried a few different combinations of if statements and grep without success. The best I could come up with is below, but I don’t think it’s working properly. My logic behind it is that if the grep is null, the user is invalid.

7 Answers 7

Just do a simple if like this:

if grep -q $address /etc/passwd then echo "OK"; else echo "NOT OK"; fi 

The -q option is used here just to make grep quiet (don’t output. )

How can this be combined with a test of variable value greater than 0? something like if grep -q $address /etc/passwd && $val > 0

Use getent and check for grep‘s exit code. Avoid using /etc/passwd. Equivalent in the shell:

getent passwd | grep -q valid_user echo $? 
getent passwd | grep -q invalid_user echo $? 
if [ -z grep $address /etc/passwd ] 

You haven’t saved the results of grep $address /etc/passwd in a variable. Before putting it in the if statement and then testing the variable to see if it is empty.

 check_address=`grep $address /etc/passwd` if [ -z "$check_address" ] then validuser=0 else validuser=1 fi 

The -z check is for variable strings, which your grep isn’t giving. To give a value from your grep command, enclose it in $():

if [ -z $(grep $address /etc/passwd) ] 

Could you try adding double quotes? if [ -z «$(grep $address /etc/passwd)» ] Edit: Also, shift your entire chunk of echos and mailing commands into the else clause if you do not want them to be run for an invalid user.

Читайте также:  Служба печати линукс минт

The easiest one will be this:

cat test123 # Output: 12345678 cat test123 | grep 123 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist" # Output: grep result exist cat test123 | grep 999 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist" # Output: grep result doesn't exist 

My problem was that the file I was trying to grep was a binary file. On windows, the first two characters in the file were little squares. On mac, the first two characters were question marks. When I used more or less on the file, I could see it was binary and when I used diff, it responded that the «Binary files foo.log and requirements.txt differ».

I used cat to display the contents of the file, highlighted and copied the text (minus the two question marks at the top, deleted the file, created a new file with touch and then used vi to paste the text back into the new file.

After that, grep worked fine.

until ! grep $address /etc/passwd ; do

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Unix using grep with if

Are you hoping that grep -x $idle is going to be reading from ./Event.log ? What do you want grep -x $idle1 to read from?

Can you explain what you’re trying to do? I can’t guess; the different pieces of your code don’t fit together in any way that makes sense to me.

Unless $idle and $dead contain exacty the same string, grep -x $idle | grep -x $dead will never return a match.

@tripleee: they could be regexes, in which case it is a reasonable way of finding the conjuction of the two. But you’re probably right that it is an error.

With -x , the entire input line must match. The output from the code mentions different «events» (in a way which suggests they are actually services or similar) so it seems highly unlikely that you need three different regexes to find one of them.

2 Answers 2

In bash, [[ is syntactically a command which is terminated with the matching ]] . It is not part of the syntax of the if command, whose syntax starts:

If you want to test whether a command succeeded or not, you just do that:

if grep -q pattern file; then # grep found pattern in file else # grep did not find pattern in file fi 

Within a [[ command, bash expects to find a conditional expression, not another command. That’s why grep -x . is a syntax error. -x is a unary operator in a conditional expression, which is true if its argument is the name of an executable file, but in that expression it is being used as though it were a binary operator.

Читайте также:  Задать mac адрес linux

If you wish to test for more than one pattern with grep , you can use the -e option to specify each option; the grep will succeed (or select) lines matching any of the options:

if grep -q -e pattern1 -e pattern2 file; then # grep found pattern1 or pattern2 in file else # grep did not find either pattern in file fi 

Источник

How to test if string exists in file with Bash?

The exit status is 0 (true) if the name was found, 1 (false) if not, so:

if grep -Fxq "$FILENAME" my_list.txt then # code if found else # code if not found fi 

Explanation

Here are the relevant sections of the man page for grep :

grep [options] PATTERN [FILE. ] 

-F , —fixed-strings

Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.

-x , —line-regexp

Select only those matches that exactly match the whole line.

-q , —quiet , —silent

Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or —no-messages option.

Error handling

As rightfully pointed out in the comments, the above approach silently treats error cases as if the string was found. If you want to handle errors in a different way, you’ll have to omit the -q option, and detect errors based on the exit status:

Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the -q or —quiet or —silent option is used and a selected line is found. Note, however, that POSIX only mandates, for programs such as grep , cmp , and diff , that the exit status in case of error be greater than 1; it is therefore advisable, for the sake of portability, to use logic that tests for this general condition instead of strict equality with 2.

To suppress the normal output from grep , you can redirect it to /dev/null . Note that standard error remains undirected, so any error messages that grep might print will end up on the console as you’d probably want.

To handle the three cases, we can use a case statement:

case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in 0) # code if found ;; 1) # code if not found ;; *) # code if an error occurred ;; esac 

Источник

Оцените статью
Adblock
detector