Sunday, December 25, 2022

Bash script functions and return statements

Bash functions, do not allow you to return a value to the caller. It can only specify 0 or 1 to mention the status of function execution is success or failure. The status value is stored in the $? variable.

To return a value from a bash function is to just set a global variable to the result. All variables in bash are global by default

promptInput(){

    echo "Please enter action number to perform"

    echo "1.Option 1"

    echo "2. Option 2"

    echo "3. Option 3"

    echo "4. Option 4"

    read action

}

promptInput

echo "User opted for " ${action}

In this, the action variable is global and the read value is stored inside action. This can be accessed outside like any other global variable using $action 

No comments:

Post a Comment