I have a scenario where I have to switch to the different user and after that, I need to execute the some Linux command.

my command is something like this

( echo myPassword | sudo -S su hduser ) && bash /usr/local/hadoop/sbin/start-dfs.sh

but with this command, I switch to the user and the next command got triggered on the previous user.

Is there any I can accomplish this using shell script

  • 6
    Be aware that this command saves your password in cleartext in your bash history file.
    – spectras
    Commented Sep 26, 2017 at 8:47

4 Answers 4



sudo -H -u TARGET_USER bash -c 'bash /usr/local/hadoop/sbin/start-dfs.sh' 

see man sudo:


The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior.

-u user

The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a user name, use #uid. When running commands as a uid, many shells require that the '#' be escaped with a backslash ('\'). Security policies may restrict uids to those listed in the password database. The sudoers policy allows uids that are not in the password database as long as the targetpw option is not set. Other security policies may not support this.

  • 6
    Why ... bash -c 'bash file.sh'? Couldn't you write it as ... bash file.sh?
    – user000001
    Commented Sep 26, 2017 at 10:53

With su user -c "sh /path/command.sh" you can run a command as user.

I tested with this command:

 echo myPassword | sudo -S su - foobar -c "/usr/bin/watch -n 1 cat /etc/resolv.conf"

After that the watch -n was running as foobar.

So I think your command should work like that:

echo myPassword | sudo -S su - hduser -c "bash /usr/local/hadoop/sbin/start-dfs.sh"

Here a shorter version of αғsнιη's answer:

sudo -Hu user command
# example: sudo -Hu root fish

You could try this one:

pkexec - Execute a command as another user

pkexec [--user username] PROGRAM [ARGUMENTS...]

  • tested on my site. But if no home dir exists, then there is an error Error changing to home directory /home/foobar: No such file or directory. I created it, but perhaps there is a better solution without home folder
    – chloesoe
    Commented Sep 26, 2017 at 10:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .