Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
More Related Contents:
- sudo echo “something” >> /etc/privilegedFile doesn’t work [duplicate]
- How do I use sudo to redirect output to a location I don’t have permission to write to? [closed]
- How to run script as another user without password?
- How do you find the original user through multiple sudo and su commands?
- How to run two commands with sudo?
- Why do my setuid root bash shell scripts not work?
- Root user/sudo equivalent in Cygwin?
- How can I execute a bash function using sudo?
- Can I export a variable to the environment from a Bash script without sourcing it?
- Passing arguments to an interactive program non-interactively
- How to urlencode data for curl command?
- How to execute a bash command stored as a string with quotes and asterisk [duplicate]
- How to pass the password to su/sudo/ssh without overriding the TTY?
- How to define hash tables in Bash?
- Why isn’t tilde (~) expanding inside double quotes? [duplicate]
- What is the difference between “$@” and “$*” in Bash? [duplicate]
- Calling shell functions with xargs
- Why piping input to “read” only works when fed into “while read …” construct? [duplicate]
- Openssh Private Key to RSA Private Key
- Parse out key=value pairs into variables
- www-data permissions?
- How to split a string in shell and get the last field
- What is
- How to write a bash script to set global environment variable?
- Hiding secret from command line parameter on Unix
- Bash Script Binary Search
- Escaping forward slashes in sed command [duplicate]
- Convert a string into an array with bash, honoring quotes for grouping [duplicate]
- Remove all files except some from a directory
- Read n lines at a time using Bash