Search code examples
bashprompt

BASH - Prompting for Answers


I'm using the following as base for asking my users for some input.

while true; do
    echo "Proceed (y/n)"
    read yn
    case $yn in
        [Nn]*) break;;
        [Yy]*)
            while true; do
                echo "name"
                read name

                echo "id"
                read id

                echo "email"
                read email

                echo "location"
                read -i "south" location

                while true; do
                    echo -e "\nIs the above correct ? (y/n)"
                    read res
                    case $res in
                        [Nn]* ) break 1;;
                        [Yy]* )
                            echo -e "\nHere we go."

                            break 3;;
                    esac
                done
            done;;
        *) echo "Please answer yes or no.";;
    esac
done

If they answer no to 'Is the above correct' they are taken back to the start of the questions.. that works fine but how do I prefill the answers with their previous answer ?

Currently when they back to the start the results are defaulted back to the original entries either blank or the default option.

Thanks


Solution

  • I would make more use of the -i option to prefill the input of the read command with the previously read value. The user can edit the value if they like. You can also use the -p option to add the prompt directly to the read command.

    location=south
    while true; do
        read -p "Proceed (y/n)" yn
        case $yn in
            [Nn]*) break;;
            [Yy]*)
                while true; do
                    read -p "Name: " -i "$name" name
                    read -p "ID: " -i "$id" id
                    read -p "Email: " -i "$email" email
                    read -p "Location: " -i "$location" location
    
                    while true; do
                        read -p "Is the above correct ? (y/n)"res
                        case $res in
                            [Nn]* ) break 1;;
                            [Yy]* )
                                echo -e "\nHere we go."
    
                                break 3;;
                        esac
                    done
                done;;
            *) echo "Please answer yes or no.";;
        esac
    done