#!/bin/bash
fun_check_password_boolean(){
Check if the $PASSWORD is good or not
TODO: if hostname can not be resolved (/etc/hosts misses 127.0.0.1)
then sudo outputs 'cannot resolve hostname', so this check
"obviously" fails.
The sudo -k command is used to invalidate the user's cached credentials for sudo.
This means that the next time you run a command with sudo, you will be prompted to
enter your password again, even if you recently authenticated.
sudo -k #disable sudo timeout, will be prompted again for passowrd
#prime it
When you use sudo -S, you typically echo the password
and pipe it into the sudo command.
&> /dev/null, this redirects both standard output (stdout) and standard error (stderr)
to /dev/null, effectively silencing any output from the command.
echo $PASSWORD | sudo -S echo hello &> /dev/null
local RESULT=$(echo $PASSWORD | sudo -S sudo -n echo hello 2>&1) if [ "$RESULT" == "hello" ]; then echo 'Correct password.' return 0 else echo 'Wrong password.' return 1 fi
}
export -f fun_check_password_boolean
Set the PASSWORD variable (be cautious about how you handle this)
PASSWORD="alexlai"
Call the function
fun_check_password_boolean
In Bash, $? is a special variable that holds the exit status of
the last command executed.
Check the return status
if [ $? -eq 0 ]; then echo "Password check passed." else echo "Password check failed." fi
fun_check_password(){ if ! fun_check_password_boolean; then echo -e "${RED}ERROR:${NC} Wrong password, we should quit now." exit 1 fi }
RED='\033[0;31m' fun_check_password