title: Run some commands as one user, and access variables set by another user
body: <p><strong>What I'm aiming for:</strong></p>
  
  <p>I want to run:</p>
  
  <ol>
  <li>multiple lines at once  </li>
  <li>under another user  </li>
  <li>with access to the variables set by the user I'm running from</li>
  </ol>
  
  <p>So from this:</p>
  
  <pre><code>ROOT_VAR='var-set-from-root'
  
  cmd="
   echo $ROOT_VAR
   echo `whoami`
   echo $HOME
  "
  </code></pre>
  
  <p>the DESIRED RESULT would be:</p>
  
  <pre><code>var-set-from-root
  UserA
  /home/UserA
  </code></pre>
  
  <p><strong>What I've tried so far:</strong></p>
  
  <p>1 run with bash; commands contained in double quotes:</p>
  
  <pre><code>cmd="
   echo $ROOT_VAR
   echo `whoami`
   echo $HOME
  "
  
  sudo -u UserA bash -c "{$cmd}"
  
  # result (has access to root var but still running as root):
  var-set-from-root
  root
  /root
  </code></pre>
  
  <p>2 run with bash with commands in heredoc</p>
  
  <pre><code>sudo -u UserA bash -c&lt;&lt;EOF
   echo $ROOT_VAR
   echo `whoami`
   echo $HOME
  EOF
  
  # result (error):
  bash: -c: option requires an argument
  </code></pre>
  
  <p>3 run with su and commands in heredoc with single quote</p>
  
  <pre><code>su UserA &lt;&lt;'EOF'
   echo $ROOT_VAR
   echo `whoami`
   echo $HOME
  EOF
  
  # result (no access to root var but running as correct user):
  
  UserA
  /home/UserA
  </code></pre>
  
  <p>4 run with su and commands in heredoc without quotes</p>
  
  <pre><code>su UserA &lt;&lt;EOF
   echo $ROOT_VAR
   echo `whoami`
   echo $HOME
  EOF
  
  # result (has access to root var but still running as root):
  var-set-from-root
  root
  /root
  </code></pre>
  
  <p>5 run with bash; commands in double quotes; root var passed as param:</p>
  
  <pre><code>cmd="
   echo $1
   echo `whoami`
   echo $HOME
  "
  
  sudo -u UserA bash -c "{$cmd}" $ROOT_VAR
  
  # result (no access to root variable parameter):
  
  root
  /root
  </code></pre>
  
  <p>None of them can access the variable set from the root user while at the same time running under the non-root user.  Is it possible even by using parameters?</p>