diff --git a/documents/references.md b/documents/references.md index bcd8f234858b6e4dfb6f8fc4fb1696a8dcd383e0..7a613a2486ff679beca52e15b236b9730e8bac22 100644 --- a/documents/references.md +++ b/documents/references.md @@ -63,3 +63,6 @@ Various references used in project. #### Check for Root User <https://stackoverflow.com/a/18216122> + +#### Get User Input +<https://ryanstutorials.net/bash-scripting-tutorial/bash-input.php> diff --git a/readme.md b/readme.md index c994898bc1f192ff989b70a93558e88b001c956b..a31ffce8ceee27fbad70db89cdea02f40bc6865c 100644 --- a/readme.md +++ b/readme.md @@ -67,6 +67,7 @@ These execute automatically on script import. * `to_lower` - Converts passed value to be fully lowercase. ### Other +* `get_user_confirmation` - Prompts user for a yes/no response. Returns True if yes. * `display_text_colors` - Displays all text color values provided by script. * `display_args_kwargs` - Displays all flags, args, and kwargs, as determined by `handle_args_kwargs()`. diff --git a/utils.sh b/utils.sh index 55c1efc983e0bd4d2ef510ef7b987fb88dcc4367..c61bce7c5f637d62fb484e124a87edcd7977e424 100755 --- a/utils.sh +++ b/utils.sh @@ -5,7 +5,8 @@ # Intended to hold very common functionality (that's surprisingly not built into bash) such as string upper/lower, # and checking current user value, and prompts of yes/no user input. # - # Version 1.0. + # https://git.brandon-rodriguez.com/scripts/bash/utils + # Version 1.1. ## @@ -504,6 +505,50 @@ function to_lower () { #region Display Functions +### + # Prompts user for yes/no confirmation. Returns True if yes. + # Accepts "yes", "ye", and "y". Input values are treated as case insensitive. + # All other values are treated as "no". + # + # Return Variable(s): return_value + ## +function get_user_confirmation () { + # Check number of passed function args. + if [[ ${#} == 0 ]] + then + # Handle prompt for no args passed. + echo -e "[${text_cyan}Yes${text_reset}/${text_cyan}No${text_reset}]" + + elif [[ ${#} == 1 ]] + then + # Handle prompt for one arg passed. + echo -e "${1} [${text_cyan}Yes${text_reset}/${text_cyan}No${text_reset}]" + + else + # Handle for too many args. + echo -e "${text_red}Too many args passed. Expected zero or one arg, received ${#}.${text_reset}" + exit 1 + fi + + # Get user input. + read -p " " return_value + echo "" + + # Convert input to lower for easy parsing. + to_lower "${return_value}" + + # Finally parse user input. + if [[ "${return_value}" == "y" || "${return_value}" == "ye" || "${return_value}" == "yes" ]] + then + # User provided "yes". Return True. + return_value=true + else + # For all other values, return False. + return_value=false + fi +} + + ### # Prints out all available text colors provided by this script. #