Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function in shell Scripting?

Tags:

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.

like image 863
user626206 Avatar asked Nov 19 '11 07:11

user626206


People also ask

How do you call a function in a shell script?

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.

How do you write and call a function in shell script?

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 [${*}]..." }

How do you call a function in bash shell?

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.

How do you call a function in Linux?

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.


2 Answers

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!

like image 79
Johnsyweb Avatar answered Oct 18 '22 10:10

Johnsyweb


#!/bin/bash  process_install() {     commands...      commands...  }  process_exit() {     commands...      commands...  }   if [ "$choice" = "true" ] then     process_install else     process_exit fi 
like image 37
user1055057 Avatar answered Oct 18 '22 09:10

user1055057