Last active
March 15, 2023 21:49
-
-
Save shirobachi/054a5d873929575e769828233d438046 to your computer and use it in GitHub Desktop.
Bunch of useful bash functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $1 - question | |
# $2 - possible answers (space separated) | |
# $3 - optional function to call with the answer | |
# $4-end - optional parameter to pass to the function | |
function answer(){ | |
QUESTION=$1 | |
POSSIBLE_ANSWERS=$2 | |
DEFAULT_ANSWER=$(echo $POSSIBLE_ANSWERS | tr ' ' '\n' | grep -oP '.*[A-Z].*' | tr '\n' ' ' | tr -d ' ') # default answer is the one what have capital letter | |
FUNCTION=$3 | |
[[ $# -ge 4 ]] && shift 3 && PARAMETERS=$* | |
DEBUG="" # Add value for prefixing debug messages and enable debug mode | |
# to lower case and remove spaces from the possible answers | |
_POSSIBLE_ANSWERS=$(echo $POSSIBLE_ANSWERS | tr '[:upper:]' '[:lower:]') | |
[[ -n $DEBUG ]] && echo "${DEBUG}Question: $QUESTION" | |
[[ -n $DEBUG ]] && echo "${DEBUG}Possible answers: $POSSIBLE_ANSWERS" | |
[[ -n $DEBUG ]] && echo "${DEBUG}Default answer: $DEFAULT_ANSWER" | |
[[ -n $DEBUG ]] && echo "${DEBUG}Function: $FUNCTION" | |
[[ -n $DEBUG ]] && echo "${DEBUG}Parameters: $PARAMETERS" | |
# Check if the answer is valid if not ask again | |
while true; do | |
# Ask the question | |
printf "$QUESTION [$(echo $POSSIBLE_ANSWERS | tr ' ' '/')]: " | |
read ANSWER | |
# if empty break | |
[[ -z $ANSWER ]] && break | |
# to lower case and remove spaces from the answer | |
ANSWER=$(echo $ANSWER | tr '[:upper:]' '[:lower:]' | tr -d ' ') | |
[[ -n $DEBUG ]] && echo "${DEBUG}Answer: $ANSWER\n" | |
# if the answer is in the list of possible answers break | |
[[ $_POSSIBLE_ANSWERS =~ $ANSWER ]] && break | |
echo -e "Invalid answer\n" | |
done | |
# If the answer is empty, use the default answer | |
[[ -z $ANSWER ]] && ANSWER=$(echo $DEFAULT_ANSWER | tr '[:upper:]' '[:lower:]') && [[ -n $DEBUG ]] && echo "${DEBUG}Answer: $ANSWER" | |
# Call the function with the answer as a parameter | |
[[ -n $FUNCTION ]] && $FUNCTION $ANSWER $PARAMETERS | |
# Return the answer | |
if [[ $3 == "return" ]]; then | |
echo $ANSWER | |
fi | |
[[ -n $DEBUG ]] && echo "${DEBUG}Answer: $ANSWER\n" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment