Execute command as another user in bash script

By neokrates, written on May 4, 2010

bash   snippet

  • Join date: 11-30-99
  • Posts: 224
View Counter:
  • 572 views
Rate it
Ad
Poll
  • Who manages CI environment in your enterprise?

    View Results

    Loading ... Loading ...
Feeds:
  • bodytext bodytext bodytext

su can execute commands under other user without interaction.

Example:

Run whoami;ls -all as $ANOTHER_USER:

su $ANOTHER_USER -l -c "whoami;ls -all"

💡 Remark: Sometimes execution fails due the different environment. In my case, I want the same environment as I had if I changed user interactively: -l.

Here is general su help:

me@my-host:~/ # su --help
Usage: su [options] [LOGIN]
 
Options:
  -c, --command COMMAND pass COMMAND to the invoked shell
  -h, --help display this help message and exit
  -, -l, --login make the shell a login shell
  -m, -p,
  --preserve-environment do not reset environment variables, and
                                keep the same shell
  -s, --shell SHELL use SHELL instead of the default in passwd
Be Sociable, Share!
 
Does that help to solve your problem?
VN:F [1.8.5_1061]
Rating: -1 (from 7 votes)
3 votes 'YES'  4 votes 'NO'
TAGS
No tags for this post.
RELATED
Pages
Posts
SOCIAL
Be Sociable, Share!

Leave a Reply