Bash: Read from User Input
From WikiMLT
Example script
Here is an example script that will execute a command depend of the user's input.
cat read-user-inpput.sh && chmod +x read-user-inpput.sh
#!/bin/bash
function user_dialog() {
local COMMAND="$1"
local DEFAULT_ANSWER="$2"
local QUESTION="\nDo you want to execute: ${COMMAND}"
if [[ $DEFAULT_ANSWER =~ ^[yY] ]]
then
DEFAULT_ANSWER="Yes";
QUESTION="${QUESTION} [Y/n]:"
else
DEFAULT_ANSWER="No";
QUESTION="${QUESTION} [y/N]:"
fi
# This line is the actual code that reads the users's input
read -rp "$(echo -e "${QUESTION}") " USER_INPUT
if [[ -z ${USER_INPUT} ]]; then USER_INPUT="$DEFAULT_ANSWER"; fi
echo -e "Accepted input: ${USER_INPUT^}"
if [[ $USER_INPUT =~ ^[yY] ]]
then
eval "$COMMAND"
else
echo -e "Skip: ${COMMAND}"
fi
}
user_dialog "touch /tmp/read-user-input.test" "y"
user_dialog "rm /tmp/read-user-input.test" "n"
./read-user-inpput.sh
Do you want to execute: touch /tmp/read-user-input.test [Y/n]: {Enter}
Accepted input: Yes
Do you want to execute: rm /tmp/read-user-input.test [y/N]: {Enter}
Accepted input: No
Skip: rm /tmp/read-user-input.test
Short version
cat read-user-inpput.sh && chmod +x read-user-inpput.sh
#!/bin/bash
function user_dialog() {
read -rp "$(echo -e "Do you want to proceed? [Y/n]:") " USER_INPUT
if [[ ${USER_INPUT:="Yes"} =~ ^[yY] ]]; then return 0; else exit; fi
}
echo "Install the dependencies"
user_dialog && sudo apt install ...
Reference manual