Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 260
Vince Avatar asked Apr 23 '26 20:04

Vince


1 Answers

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"
like image 103
kamituel Avatar answered Apr 26 '26 10:04

kamituel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!