Vince
Vince

Reputation: 1133

bash yes no function

I have many Yes/No answers in my script. How can I create a function to minimize the size of my script?

I have the following:

function ask {
    read -n 1 -r
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
            return 1;
    else
            exit
            echo "Abort.."
    fi
}

ask "Continue? [y/N] "

It works fine. But the Question "Continue? [y/N] is not displayed. How can I "transfer" this text to my function

Upvotes: 3

Views: 4155

Answers (1)

kamituel
kamituel

Reputation: 35950

You can use $1 variable:

function ask {
    echo $1        # add this line
    read -n 1 -r
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
            return 1;
    else
            exit
            echo "Abort.."
    fi
}

Edit: as noted by @cdarke, 'echo' call can be avoided thanks to '-p' switch in read:

# echo $1
# read -n 1 -r
read -n 1 -r -p "$1"

Upvotes: 4

Related Questions