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.
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.
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 [${*}]..." }
To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.
1. using function keyword : A function in linux can be declared by using keyword function before the name of the function. Different statements can be separated by a semicolon or a new line.
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!
#!/bin/bash process_install() { commands... commands... } process_exit() { commands... commands... } if [ "$choice" = "true" ] then process_install else process_exit fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With