Checking if output of a command contains a certain string in a shell script

后端 未结 4 725
谎友^
谎友^ 2020-11-29 18:14

I\'m writing a shell script, and I\'m trying to check if the output of a command contains a certain string. I\'m thinking I probably have to use grep, but I\'m not sure how.

相关标签:
4条回答
  • 2020-11-29 18:25

    Testing $? is an anti-pattern

    if ./somecommand | grep -q 'string'; then
      echo "matched"
    fi
    
    0 讨论(0)
  • 2020-11-29 18:32

    Another option is to check for regular expression match on the command output.

    For example:

    [[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"
    
    0 讨论(0)
  • 2020-11-29 18:33

    Test the return value of grep:

    ./somecommand | grep 'string' &> /dev/null
    if [ $? == 0 ]; then
       echo "matched"
    fi
    

    which is done idiomatically like so:

    if ./somecommand | grep -q 'string'; then
       echo "matched"
    fi
    

    and also:

    ./somecommand | grep -q 'string' && echo 'matched'
    
    0 讨论(0)
  • 2020-11-29 18:45

    A clean if/else conditional shell script:

    if ./somecommand | grep -q 'some_string'; then
      echo "exists"
    else
      echo "doesn't exist"
    fi
    
    0 讨论(0)
提交回复
热议问题