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="mlw-continue">
<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="mlw-continue">
<syntaxhighlight lang="bash" line="1" class="code-continue">
#!/bin/bash
#!/bin/bash



Latest revision as of 08:28, 26 September 2022

Ex­am­ple script

Here is an ex­am­ple script that will ex­e­cute a com­mand de­pend of the user's in­put.

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 ver­sion

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 ...

Ref­er­ence man­u­al