sudo, runuser, su don't work as I expect when run as root with command as "echo $HOME"

9,079

Solution 1

Tangentially related:

sudo -u someuser -i "echo $HOME"

doesn't work at all for me. It says:

-bash: echo $HOME: command not found

To the point: When you execute the command

sudo -u someuser -i echo $HOME

the variable $HOME gets expanded by the shell before sudo gets even executed.

To solve this, you could use a command like

sudo -u someuser -i bash -c 'echo $HOME'

In this command, echo $HOME gets sent literally to bash after switching the UID.

The result is as expected:

/home/someuser

Solution 2

When you do

 su - someuser -c "echo $HOME"

The current shell expands $HOME first, then the result is passed through to the command (su in this case) and thence to a shell process running as the new user.

Try protecting the variable with single quotes

 su - someuser -c 'echo $HOME'
Share:
9,079

Related videos on Youtube

nelaaro
Author by

nelaaro

Linux admin, tech enthusiast. opensource evangelist.

Updated on September 18, 2022

Comments

  • nelaaro
    nelaaro over 1 year

    When I run these commands it outputs as shown. /root

    $ sudo -u someuser -i "echo $HOME"
    /root
    $ runuser -l someuser -c "echo $HOME"
    /root    
    $ su - someuser -c "echo $HOME"
    /root
    

    What i expected was

    /home/someuser
    

    When I run the env command to inspect the environment It reports the HOME variable correctly.

    $ su - someuser -c "env"
    ...  
    HOME=/home/someuser
    ...
    
    $ sudo -u someuser -i "env"  
    ...  
    HOME=/home/someuser
    ...
    
    $ runuser -l someuser -c "env"  
    ...  
    HOME=/home/someuser
    ...  
    

    What I want to do is run scripts under the users home directory. /home/someuser/scripts.
    as ${HOME}/scripts/somescript.sh

    $ sudo -u someuser  ${HOME}/scripts/somescript.sh
    sudo: /root/scripts/somescript.sh: command not found  
    

    What i expected was:

    $ sudo -u someuser  ${HOME}/scripts/somescript.sh
    ...
    script output.
    ...
    
  • nelaaro
    nelaaro over 11 years
    bash command line expansion, seams like a silly mistake to make.