I have a bash script where I need to prompt for a password. I'm using whiptail to capture the password. I need to be able to differentiate between an empty password and the "Cancel" button being selected. Cancel normally returns an error code of 1.
Why does the following code not detect the user selecting the "Cancel" button?
#!/bin/bash
function get_password() {
local password=`whiptail --clear \
--title "Password" \
--passwordbox "Enter your login password:" \
8 68 \
2>&1 >/dev/tty`
local err=$?
if [ "$err" -ne 0 ]; then
>&2 echo "Cancelled"
return 1
fi
if [ -z "$password" ]; then
>&2 echo "No password entered"
return 1
fi
echo "Password entered: $password"
}
get_password
I figured out that I can make it work by changing local password to password, effectively storing it in a global variable rather than a local variable. I'd like to avoid doing that, but I can't figure out how to make it work. Is there a proper way of doing this with local variables?
canceldetection ?errset to 1 if the user cancels it. If I remove thelocalkeyword (makingpassworda global variable), the code will properly detect the cancel button being selected.