Execute command as another user in bash script

By neokrates, written on May 4, 2010

bash   snippet

Rate it
  • 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
    Loading ... Loading ...
Ad
Poll
  • Which virtualization is used on your Enterprise?

    • We don't use virtulization (90%, 9 Votes)
    • VM Ware (10%, 1 Votes)
    • Virtual Box (0%, 0 Votes)
    • Parallels (0%, 0 Votes)
    • coLinux (0%, 0 Votes)
    • Xen (0%, 0 Votes)
    • OpenVZ (0%, 0 Votes)
    • Something else (0%, 0 Votes)

    Total Voters: 10

    Vote

    Loading ... Loading ...
Feeds:
  • bodytext bodytext bodytext
Most popular search terms:

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"


[i] 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
 
Does that help to solve your problem?
VN:F [1.8.5_1061]
Rating: 0 (from 6 votes)
3 votes 'YES'  3 votes 'NO'
TAGS
No tags for this post.
RELATED
Pages
Posts
    nope :(
SOCIAL
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlinkList
  • Blogosphere News
  • E-mail this story to a friend!
  • Furl
  • LinkArena
  • Live
  • MisterWong
  • Print this article!
  • StumbleUpon
  • Technorati
  • Webnews.de
  • YahooMyWeb

Leave a Reply