If grep finds what it is looking for do X else Y

You can use the entire grep pipeline as the condition of the if statement. Use grep -q to keep it from printing the match it finds (unless you want that printed). I also simplified the exit (there's no need to store $? in a variable if you're just going to use it immediately). Here's the result:

if find "/app/$var1" -maxdepth 1 -type l -o -type d | grep -q "$var2"; then
    $realcmd "$@"
    exit $?
else
    echo "no match, the version you are looking for does not exist"
    # Should there be an exit here?
fi

BTW, since you're going to exit immediately after $realcmd, you could use exec $realcmd "$@" to replace the shell with $realcmd instead of running $realcmd as a subprocess.


From the grep manpage:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2.

In other words, immediately following your blah blah | grep $var2, simply check the return value.

Since the exit code for a pipeline is the exit code for the last process in that pipeline, you can use something like:

find /app/$var1 -maxdepth 1 -type l -o -type d | grep $var2 ; greprc=$?
if [[ $greprc -eq 0 ]] ; then
    echo Found
else
    if [[ $greprc -eq 1 ]] ; then
        echo Not found
    else
        echo Some sort of error
    fi
fi

Tags:

Bash

Grep