Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Scripting: Can you make a function call itself?

Tags:

bash

shell

I'm making a bash script with a simple interactive menu that asks a yes or no question. I'm wondering if I can use a function to call itself and restart the prompt if the person writes random junk, is this possible?

Code:

Question () {
read -r -p "yes or no quesiotn [Y/N]"
Response

case Response in
    Y|y)
        #some code
        ;;
    N|n)
        #more code
        ;;
    *) 
        ehco "im sorry i didnt catch that"
        Question
        ;;
    esac
}

Question
like image 897
gomilksolgo Avatar asked Aug 06 '26 19:08

gomilksolgo


1 Answers

Instead of calling itself, make the function return appropriate exit codes, (a 1 for failed, a 0 for success), then have a do-nothing until loop do the work:

Question () {
            read -r -p "Yes or no question [Y/N]?" Response
            case "$Response" in
                 Y|y)
                     #some code
                     ;;
                 N|n)
                     #more code
                     ;;
                 *) 
                     echo "I'm sorry I didn't catch that."
                     return 1
                     ;;
            esac
            }


until Question ; do : ; done
like image 194
agc Avatar answered Aug 08 '26 12:08

agc



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!