How to check if grep has no output?

前端 未结 5 1361
借酒劲吻你
借酒劲吻你 2020-12-15 03:17

So I need to check if the recipient username is in /etc/passwd which contains all the users in my class, but I have tried a few different combinations of if statements and g

相关标签:
5条回答
  • 2020-12-15 03:19

    Your piece of code

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

    You haven't save 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.

    You can try it like this

        check_address=`grep $address /etc/passwd`
        if [ -z "$check_address" ]
          then
        validuser=0
        else
            validuser=1
        fi
    
    0 讨论(0)
  • 2020-12-15 03:25

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

    0 讨论(0)
  • 2020-12-15 03:26

    easiest one will be this

    $ cat test123
    12345678
    
    $ cat test123 | grep 123 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
    grep result exist
    
    $ cat test123 | grep 999 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
    grep result doesn't exist
    
    
    0 讨论(0)
  • 2020-12-15 03:29

    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) ]
    
    0 讨论(0)
  • 2020-12-15 03:31

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

    > getent passwd | grep -q valid_user
    > echo $?
    0
    
    > getent passwd | grep -q invalid_user
    > echo $?
    1
    
    0 讨论(0)
提交回复
热议问题