|
OSXFAQ Mac OS X UNIX Tip-of-the-Day
Scripting One-Liners - Authentication
This week's tips give some useful one-lines that you can incorporate into your Bash scripts.
Suppose you have a script that uses 'sudo' to execute a command as root. When the script executes sudo, the user must authenticate with a password. If the user fails to authenticate then sudo will not run the command and we must terminate the script.
If the script is already part-way through execution we might have to undo some of the stages its already gone through. Ideally, we want to achieve authentication at the start of the scrip, even though the command that requires it occurs later.
To do this we rely on the fact that a sudo authentication is valid for five minutes. Place this line at the start of the script:
sudo -p Admin password echo 2> /dev/null || { echo Incorrect ; exit; }
How does it work? Option -p causes sudo prints a prompt. The sudo command just executes a null echo command. If authentication is not successful, sudo returns failure (or False) and the following statement (after the || 'OR') operator is executed. This statement prints an error message and exits.
If authentication is successful, sudo returns success (or True) and the second statement is skipped.
An OR operator executes its statements only in order to produce a Boolean result, True or False. It reasons that if the first statement yields True, then the second statement needn't be executed because it won't affect the overall result - True OR anything = True.
Similarly, the AND operator (&&) doesn't execute its second statement if the first yields False - False AND anything = False.
|