How do I run a script as a different user?
Running Script as Another User. By default, the su command takes an input a target username to switch into. However, we can specify a script to be run with the flag -c. When specified, su command will just execute the script without dropping into a new shell as the target user.
How do I run a script as root?
- open terminal.
- run sudo chown root:wheel /usr/local/bin/the-script.sh.
- run sudo chmod u+rwx /usr/local/bin/the-script.sh (to allow root reading, writing and executing)
- run sudo chmod go-w+rx /usr/local/bin/the-script.sh (to allow everyone to execute and read, but writing)
How do I sudo to another user?
Another way to switch to another account with sudo is to use the -s option. If you run sudo -s that will start a shell as root. You can specify a user with the -u option….Using sudo.
| Commands | Meaning |
|---|---|
| sudo command | Run command as root. |
| sudo -u root command | Run command as root. |
| sudo -u user command | Run command as user. |
How to use sudo without password in script stack?
As mentioned by Basilevs you need to add your user to the sudoers file in order to avoid that sudo commands in the script get stuck awaiting the password. On Ubuntu 16, there is a simpler way: just add the user to the sudo group, like this: sudo usermod -aG sudo *username* From then on, it should work like a charm.
Can a script be run without Sudo privileges?
That way, all commands within the script will be run with root privileges and you only need to give the password once when launching the script. If you need a particular command within the script to be run without sudo privileges, you can run it as a regular user with (thanks Lie Ryan ):
How can I execute any command as a normal user without Sudo?
This is possible by editing /etc/sudoers with the visudo command, and with the use of the alias shell built-in. Give yourself permission to sudo execute the commands without requiring a password prompt. Now you may type those commands and execute them without sudo, as though you were currently in a root shell.
How to find the root user of a Sudo script?
However, in case you want to drop root privileges to some of the commands and run them as the actual user who invoked the command with sudo, you can check for the $SUDO_USER variable to figure out the original user. #!/bin/bash # ref: https://askubuntu.com/a/30157/8698 if ! [ $ (id -u) = 0 ]; then echo “The script need to be run as root.”