user626206 user626206 - 2 months ago 6
Bash Question

How to call a function in shell Scripting?

I have a shell script which conditionally calls a function.

For Example:-

if [ "$choice" = "true" ]
then
process_install
elif [ "$choice" = "false" ]
then
process_exit
fi

process_install()
{
commands...
commands...
}

process_exit()
{
commands...
commands...
}


Please let me know how to accomplish this.

Answer

You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:

#!/bin/sh

Please remember to tag future questions with the shell type, as this will help the community answer your question.

You need to define your functions before you call them. Using ():

process_install()
{
    echo "Performing process_install() commands, using arguments [${*}]..."
}

process_exit()
{
    echo "Performing process_exit() commands, using arguments [${*}]..."
}

Then you can call your functions, just as if you were calling any command:

if [ "$choice" = "true" ]
then
    process_install foo bar
elif [ "$choice" = "false" ]
then
    process_exit baz qux

You may also wish to check for invalid choices at this juncture...

else
    echo "Invalid choice [${choice}]..."
fi

See it run with three different values of ${choice}.

Good luck!

Comments