Reputation: 183
I've been working with bash for not more than 6 hours, and now I'm trying to create a menu that allows you to do some "fun" stuff :D.
My problem is with the if statement that check if you're in sudo mode. I want to have 3 conditions:
2)
if [ "$EUID" -ne 0 ]
then
echo "Checking if you are in sudo mode..."
echo "Error, please insert your password:"
sudo ls /root
if [ "$EUID" -ne 0 ]
then
echo -e "\nCould not authenticate the user."
echo -e "For security reasons the application will be closed."
exit
else
echo "==============================================================="
echo -e "ALL COPIES HAVE A DEFAULT ROUTE: /home/patryk/Desktop/a/"
echo "==============================================================="
echo -e "Enter the path of the folder to be copied: "
read origin
rsync -avzh $origin /home/patryk/Desktop/a/`date-I`
fi
else
echo "==============================================================="
echo -e "ALL COPIES HAVE A DEFAULT ROUTE: /home/patryk/Desktop/a/"
echo "==============================================================="
echo -e "Enter the path of the folder to be copied: "
read origin
rsync -avzh $origin /home/patryk/Desktop/a/`date -I`
fi;;
Upvotes: 18
Views: 15934
Reputation: 11
I am running sudo 1.9.13p2 on MAC OSX, and sudo has a -l option to do that, so in a bash script:
if sudo -l > /dev/null; then
echo "This is sudoed"
else
echo "This is NOT sudoed"
fi
Upvotes: 0
Reputation: 906
if pgrep -s 0 '^sudo$' > /dev/null ; then
echo 'Hello Sudo'
else
echo 'Hello Chestnut'
fi
Upvotes: 1
Reputation: 27340
If you have sudo credentials caching enabled (that is, after a successful sudo, you don't have to enter the password again for subsequent sudos) you could use the following trick:
Execute sudo true
and check the return status. If the correct password was entered, the exit code will always be 0
. Otherwise the exit code will be different.
if [[ "$EUID" = 0 ]]; then
echo "(1) already root"
else
sudo -k # make sure to ask for password on next sudo ✱
if sudo true; then
echo "(2) correct password"
else
echo "(3) wrong password"
exit 1
fi
fi
# Do your sudo stuff here. Password will not be asked again due to caching.
✱ Assuming a standard configuration, where you have to enter your password at least sometimes when using sudo
. If your user is configured for passwordless sudo
(see NOPASSWD
in/etc/sudoers
) then this won't work.
Upvotes: 24
Reputation: 21
I think what you really want to do is to check whether your script runs as root or not. If security considerations are not super duper important you could just throw this at the beginning of your script:
if [ "$USER" != "root" ]
then
echo "Please run this as root or with sudo"
exit 2
fi
This will work and also cover the case where sudo is used to run command as another user (who is not root)
Upvotes: 1