Prompt for sudo password and programmatically elevate privilege in bash script?
I run sudo
directly from the script:
if [ $EUID != 0 ]; then
sudo "$0" "$@"
exit $?
fi
Add this as the first line of the script:
[ "$UID" -eq 0 ] || exec sudo bash "$0" "$@"
Change sudo
to gksu
or gksudo
if you prefer a graphical prompt.
I suggest:
#!/bin/bash
if (($EUID != 0)); then
if [[ -t 1 ]]; then
sudo "$0" "$@"
else
exec 1>output_file
gksu "$0 $@"
fi
exit
fi
# some example stuff
ls -l /root
echo "app: $0"
for f; do
echo ">$f<"
done