title: How to get $HOME directory when switching to a different user in bash?
body: <p>I need to execute part of a bash script as a different user, and inside that user's <code>$HOME</code> directory. However, I'm not sure how to determine this variable. Switching to that user and calling <code>$HOME</code> does not provide the correct location:</p>
  
  <pre><code># running script as root, but switching to a different user...
  su - $different_user
  echo $HOME
  # returns /root/ but should be /home/myuser
  </code></pre>
  
  <h3>Update:</h3>
  
  <p>It appears that the issue is with the way that I am trying to switch users in my script:</p>
  
  <pre><code>$different_user=deploy
  
  # create user
  useradd -m -s /bin/bash $different_user
  
  echo "Current user: `whoami`"
  # Current user: root
  
  echo "Switching user to $different_user"
  # Switching user to deploy
  
  su - $different_user
  echo "Current user: `whoami`"
  # Current user: root
  echo "Current user: `id`"
  # Current user: uid=0(root) gid=0(root) groups=0(root)
  
  sudo su $different_user
  # Current user: root
  # Current user: uid=0(root) gid=0(root) groups=0(root)
  </code></pre>
  
  <p>What is the correct way to switch users and execute commands as a different user in a bash script?</p>