NOTE:
- you probably shouldn't do this (use
sudo
instead if you can) - preserves stdin and cli args but not env vars (only PATH makes it through)
- test example script with
./make-it-root.sh with params <<<"and stdin"
#!/usr/bin/env bash | |
# $ ./make-it-root.sh with params <<<"and stdin" | |
set -e | |
# if not run as root, prompt user to allow this to run as root | |
# NOTE: Must use `whoami`, $USER won't be set when run this way, which will cause this to trigger recursively | |
if [[ "$(whoami)" != 'root' ]]; then | |
exec osascript - "$0" "$@" 3<&0 <<APPLESCRIPT | |
on run argv | |
set stdin to do shell script "cat 0<&3" | |
set command to "" | |
repeat with arg in argv | |
set command to command & quoted form of arg & " " | |
end repeat | |
do shell script (command & " <<< " & quoted form of stdin) with administrator privileges | |
end run | |
APPLESCRIPT | |
fi | |
# do stuff as root | |
echo "do stuff as $(whoami) with params ($0 $*) and stdin $(cat)" | |
# NOTE: it's not just $USER missing, for me $PATH is the only environment variable preserved... | |
env |