title: Check Whether a User Exists
body: <p>I want to create a script to check whether a user exists. I am using the logic below:</p>
  
  <pre><code># getent passwd test &gt; /dev/null 2&amp;&gt;1
  # echo $?
  0
  # getent passwd test1 &gt; /dev/null 2&amp;&gt;1
  # echo $?
  2
  </code></pre>
  
  <p>So if the user exists, then we have success, else the user does not exist. I have put above command in the bash script as below:</p>
  
  <pre><code>#!/bin/bash
  
  getent passwd $1 &gt; /dev/null 2&amp;&gt;1
  
  if [ $? -eq 0 ]; then
      echo "yes the user exists"
  else
      echo "No, the user does not exist"
  fi
  </code></pre>
  
  <p>Now, my script always says that the user exists no matter what:</p>
  
  <pre><code># sh passwd.sh test
  yes the user exists
  # sh passwd.sh test1
  yes the user exists
  # sh passwd.sh test2
  yes the user exists
  </code></pre>
  
  <p>Why does the above condition always evaluate to be TRUE and say that the user exists?</p>
  
  <p>Where am I going wrong?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>After reading all the responses, I found the problem in my script. The problem was the way I was redirecting <code>getent</code> output. So I removed all the redirection stuff and made the <code>getent</code> line look like this:</p>
  
  <pre><code>getent passwd $user  &gt; /dev/null
  </code></pre>
  
  <p>Now my script is working fine.</p>