Bash: Read from User Input: Difference between revisions
From WikiMLT
m Spas moved page Bash Read from User Input to Bash: Read from User Input without leaving a redirect |
m Text replacement - "mlw-continue" to "code-continue" |
||
Line 6: | Line 6: | ||
cat read-user-inpput.sh && chmod +x read-user-inpput.sh | cat read-user-inpput.sh && chmod +x read-user-inpput.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="bash" line="1" class=" | <syntaxhighlight lang="bash" line="1" class="code-continue"> | ||
#!/bin/bash | #!/bin/bash | ||
Line 56: | Line 56: | ||
cat read-user-inpput.sh && chmod +x read-user-inpput.sh | cat read-user-inpput.sh && chmod +x read-user-inpput.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="bash" line="1" class=" | <syntaxhighlight lang="bash" line="1" class="code-continue"> | ||
#!/bin/bash | #!/bin/bash | ||
Latest revision as of 07:28, 26 September 2022
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