Skip to content

Instantly share code, notes, and snippets.

@ciiqr
Last active October 9, 2022 04:47
Show Gist options
  • Save ciiqr/9f02ebf48a5e25fd44d52dd597d869e1 to your computer and use it in GitHub Desktop.
Save ciiqr/9f02ebf48a5e25fd44d52dd597d869e1 to your computer and use it in GitHub Desktop.
macos rerun script as root with (gui) user prompt

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment