Conditional when based on grep results

Hey all,

So I’m trying to do a check to see if a string exists in a file and to add if it does not.

This is what I have:

  • name: exists in file
    command: “grep string /var/log/file”
    register: string_not_exist

  • name: run_if_exists
    command: “touch /tmp/add”
    when: string_not_exist.stdout == 1

This doesn’t work. :frowning: Any help would be appreciated!!

Chris,

Try string_not_exist.rc > 0 or string_not_exist.rc == 1. Grep will not return to stdout if the string does not exist in the log file—the command will return (rc = return code) an exit code of 1.

For example:

echo “test test test” | grep string
echo $?
1

Hope this helps.