• Uncategorized

About bash : what-is-the-best-way-to-go-back-to-the-beginning-of-a-script

Question Detail

I have a script with several inputs, the script eventually initiates a download, once the download is complete i would like to do prompt the user to start the process over if they want to download something else.

while true;do
    read -p "Is this correct? (yes/no/abort) " yno
    case $yno in
        [Yy]*) break;;
        [Nn]*) echo "Lets Start Over" 'restart script code goes here';;
        [Aa]*) exit 0;;
            *) echo "Try again";;

    esac
done

echo
echo "Starting $build download for $opt1 from Jenkins"
echo

while true;do
    read -p "Do you want to download something else? " yesno
    case $yesno in
        [Yy]* ) 'restart script code goes here';;
        [Nn]* ) break;;
        * ) echo "Try Again "
    esac
done

Question Answer

If you design your shell script with shell functions, repeating a chunk of code gets much easier:

main() {
    while true; do
        next
        if ! validate_opt 'Do you want to download something else?'; then
            break
        fi
    done
}
validate_opt() {
    local PS3="$1 (Press ctrl-c to exit) "
    local choice
    select choice in yes no; do
        # This can be written more tersely,
        # but for clarity...
        case $choice in
            yes) return 0;;
             no) return 1;;
        esac
    done
}
do_download() {
    echo
    echo "Starting $build download for $opt1 from Jenkins"
    echo
    fetch "$1" # or whatever
}
next() {
    if validate_opt 'Is this correct?'; then
        do_download "$opt"
    else
        echo "Let's start over"
    fi
}
main

function stage1 {
while true;do
    read -p "Is this correct? (yes/no/abort) " yno
    case $yno in
        [Yy]*) stage2;;
        [Nn]*) continue;;
        [Aa]*) exit 0;;
            *) echo "Try again";;

    esac
done
}

function stage2 {
echo
echo "Starting $build download for $opt1 from Jenkins"
echo

while true;do
    read -p "Do you want to download something else? " yesno
    case $yesno in
        [Yy]* ) stage1;;
        [Nn]* ) exit 0;;
        * ) echo "Try Again ";;
    esac
done

}
stage1

You can do this using functions

The first function is stage 1 and the second stage2
After listing all the functions, at the bottom of the file we call stage1.
when the function stage1 executes and $yno= Y* or y* , it will skip to the stage2 function, vice versa when we in stage2

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.