# Conditional when based on grep results

**URL:** <https://forum.ansible.com/t/conditional-when-based-on-grep-results/28555>\
**Category:** Ansible Project\
**Created:** [September 11, 2018, 10:50pm UTC](https://forum.ansible.com/t/conditional-when-based-on-grep-results/28555 "2018-09-11T22:50:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chris\_Bidwell](https://avatars.discourse-cdn.com/v4/letter/c/da6949/32.png) [@Chris\_Bidwell](https://forum.ansible.com/u/Chris_Bidwell)\
**Post date:** [September 11, 2018, 10:50pm UTC](https://forum.ansible.com/t/conditional-when-based-on-grep-results/28555/1 "2018-09-11T22:50:08Z")

</div>

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. ☹ Any help would be appreciated!!

---

<div class="post-metadata">

**Author:** ![Edward](https://avatars.discourse-cdn.com/v4/letter/e/90db22/32.png) [@Edward](https://forum.ansible.com/u/Edward)\
**Post date:** [September 11, 2018, 11:01pm UTC](https://forum.ansible.com/t/conditional-when-based-on-grep-results/28555/2 "2018-09-11T23:01:35Z")

</div>

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.
