Shell Script – How to Bypass a Function if Already Executed

shell-scriptvariable

I have a function prereq() that may be invocated several times but should not actually be executed more than once on the same running thread of the script by selecting other options from the menu (each option on the menu will have prereq() as part of the code):

# Pre-requirements
prereq ()
{
        echo
        echo "########################## CHECKING PRE-REQUIREMENTS ##########################"
        echo "#                                                                             #"
        echo "Required packages: hdparm, fio, sysbench, iperf3 and sshpass"
        sleep 2
        echo
        for pack in hdparm fio sysbench iperf3 sshpass; do
                echo "Checking and if needed install '$pack'..."
                if ! rpm -qa | grep -qw "$pack"; then
                        yum install -y $pack > /dev/null
                else
                        echo "$pack is already installed, skipping..."
                        echo
                fi
        done
        echo "###############################################################################"
echo
}

The function is executed like below:

select opt in "${options[@]}"
do
        case $opt in
        "CPU Stress Test (local)")
                sleep 2
                prereq                ===>> HERE IS!
                cpu
                cleanup
                echo
                break
        ;;
        "Memory Stress Test (local)")
                sleep 2
                prereq                ===>> HERE IS!
                memory
                cleanup
                echo
                break
                .
                .
                .

I need to execute prereq() just once even if selecting other options from the menu that's invocate prereq() because each function can be executed once and the purpose of the script is done, and it can be exited.

I am planning to have a variable on prereq() as a flag and if it's executed, the flag is checked every time that prereq() is invocated on any option from the menu.

Furthermore, I appreciate any help! Thanks!

Best Answer

Since shell variables are global unless you declare them as local inside a function (a mean trap by the way), you can simply define a variable

prereq_done=0

on top of the script and then modify the prereq() function to check for it at the beginning (exit if it is already set), and set it to 1 at the end:

prereq()
{
  if (( prereq_done == 1 )); then return; fi

  < your code here >

  prereq_done=1
}
Related Question