Search code examples
bashsudosu

Set variable in bash script sudo with heredoc


I'm trying to run a script which switches users (following this answer). I'm unable to set a variable within this. I've tried many things but the most basic is:

sudo -u other_user bash << EOF
V=test
echo "${V}"
EOF

More realistically I am doing something similar to the following:

sudo -u other_user bash << EOF
cd
V=$(ls)
echo "${V}"
EOF

Every time I try to use the variable V it is unset. How can I set a variable?


Solution

  • To suppress all expansions within the heredoc, quote the sigil -- that is, <<'EOF', not <<EOF:

    sudo -u other_user bash -s <<'EOF'
    cd
    v=$(ls)      # aside: don't ever actually use ls programmatically
                 #        see http://mywiki.wooledge.org/ParsingLs
    echo "$v"    # aside: user-defined variables should have lowercase names; see
                 #        http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
                 #        fourth paragraph ("the name space of environment variable names
                 #        containing lowercase letters is reserved for applications.")
    EOF
    

    If you want to pass variables through, pass them after the -s, and refer to them positionally from in the heredoc script (as $1, $2, etc).