Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Created November 17, 2023 04:11
Show Gist options
  • Save nyteshade/5f6a180c715d11330f8a3c1e5d042d94 to your computer and use it in GitHub Desktop.
Save nyteshade/5f6a180c715d11330f8a3c1e5d042d94 to your computer and use it in GitHub Desktop.
Prompt user with binary question
#!/usr/bin/env zsh
promptUser() {
# Check if no parameters are supplied
if [[ $# -eq 0 ]]; then
echo "Usage: promptUser <message> [positiveWord] [negativeWord]"
return 1
fi
local message=$1
local positiveWord=${2:-Yes}
local negativeWord=${3:-No}
local response
local positiveStringKey="\x1b[1m${positiveWord:0:1}\x1b[0m${positiveWord:1}"
local negativeStringKey="\x1b[1m${negativeWord:0:1}\x1b[0m${negativeWord:1}"
local positiveKey="${positiveWord:0:1}"
local negativeKey="${negativeWord:0:1}"
local negativeDisplay=$(echo "$negativeWord" | awk '{print tolower($0)}')
# Display the message with the formatted prompt
printf "$message (${positiveStringKey}/${negativeStringKey}): "
# Continuously wait for the correct input
while true; do
# Read a single character silently (no echo)
read -s -k 1 response
# Convert input to lowercase for comparison
local lowerResponse=${response:l}
local lowerPositiveKey=${positiveKey:l}
local lowerNegativeKey=${negativeKey:l}
if [[ $lowerResponse == $lowerPositiveKey ]]; then
echo "$positiveWord"
break
elif [[ $lowerResponse == $lowerNegativeKey ]]; then
echo "$negativeWord"
break
fi
# If invalid input, continue the loop without printing anything
done
}
# Function to check if script is sourced
is_script_sourced() {
if [[ -n $ZSH_VERSION ]]; then
# For Zsh
(( ${#funcstack[@]} > 1 ))
elif [[ -n $BASH_VERSION ]]; then
# For Bash
(( ${#BASH_SOURCE[@]} > 1 ))
else
# Default to false
return 1
fi
}
# Detect if the script is being sourced or run directly
if is_script_sourced; then
true
else
promptUser ${@}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment