This is a script that I, this unix forum and stackoverflow come up with. I would like to get some feedback about it and improve it little bit if possible for even more readability and better working. OR get some shaming hilarious opinion.
#!/bin/bash
currentShell=$(readlink /proc/$$/exe);
if [ "$currentShell" != "/bin/bash" ]
then
echo 'The script is ran by different shell, not Bash shell, be cautious next time.';
echo 'I will rerun this script with Bash shell for You, to avoid unusual behaviour';
exec bash "$0" "$@";
fi
declare sudoPasswordCache=$((sudo -n true) 2>&1);
if [ "$sudoPasswordCache" = "sudo: a password is required" ];
then
echo ""
echo 'This script is required to be ran as root user.';
echo 'You will be asked for a password';
#else echo 'You have a cached password in place, no need for password.'
fi
if [ "$EUID" -ne 0 ];
then
exec sudo bash "$0" "$@";
echo "exec failed" >&2
exit 1;
fi
Not everyone has readlink. You can check the SHELL variable instead, it's quite standard.
Use [[ "$VAR1" == "value" ]] as single-equals and single square-braces are now archaic.
Automatically rerunning it with BASH is begging for an infinite loop if anything weird happens. You also didn't check if that exec failed.
Error messages should go to stderr, a la
echo 'The script is ran by different shell, not Bash shell, be cautious next time.' >&2
Otherwise, people may find big flat error messages in their flatfiles whenever they redirect the output.
You don't need to and probably shouldn't be checking the text output of sudo -- just get its return value. There's also no reason to use a sub-shell, or a sub-sub-shell within that sub-shell. You can put it right into the if-statement as if it belongs there, which it does, with an ! in front to invert the return value.
if ! sudo -n true </dev/null 2>/dev/null
then
echo 'This script is required to be ran as root user.' >&2
echo 'You will be asked for a password.' >&2
fi