Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a function of a shell script from another shell script?

Tags:

shell

unix

I have 2 shell scripts.

The second shell script contains following functions second.sh

func1  func2 

The first.sh will call the second shell script with some parameters and will call func1 and func2 with some other parameters specific to that function.

Here is the example of what I am talking about

second.sh

val1=`echo $1` val2=`echo $2`  function func1 {  fun=`echo $1` book=`echo $2`  }  function func2 {  fun2=`echo $1` book2=`echo $2`   } 

first.sh

second.sh cricket football  func1 love horror func2 ball mystery 

How can I achieve it?

like image 567
avirup Avatar asked May 30 '12 19:05

avirup


People also ask

How do you pass a parameter to a shell script from another shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

Can we call a function inside a function in shell script?

In the myScript.sh file, we've defined a variable VAR and two functions: log_info() and log_error(). We can call the functions within the script file.

How do you call a function in a Unix script?

The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.


1 Answers

Refactor your second.sh script like this:

func1 {    fun="$1"    book="$2"    printf "func=%s,book=%s\n" "$fun" "$book" }  func2 {    fun2="$1"    book2="$2"    printf "func2=%s,book2=%s\n" "$fun2" "$book2" } 

And then call these functions from script first.sh like this:

source ./second.sh func1 love horror func2 ball mystery 

OUTPUT:

func=love,book=horror func2=ball,book2=mystery 
like image 133
anubhava Avatar answered Sep 23 '22 14:09

anubhava