Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a shell script and pass argument from another shell script

Tags:

shell

unix

I'm calling a shell script from another shell script and the called script requires some input (command line) parameters.
I'm have below mentioned code, but thats not working. I don't know why the argument values are not passed to the called script.

script1.sh
=======================================
#!/bin/bash
ARG1="val1"
ARG2="val2"
ARG3="val3"
. /home/admin/script2.sh "$ARG1" "$ARG2" "$ARG3"


script2.sh
=======================================
#!/bin/bash
echo "arg1 value is: $1 ....."
echo "arg2 value is: $2 ....."
echo "arg3 value is: $3 ....."

But when I execute script1.sh I get following result:

arg1 value is:  .....
arg2 value is:  .....
arg3 value is:  .....

What am I missing?

like image 538
user85 Avatar asked Jan 13 '13 09:01

user85


People also ask

How do you pass an argument into a shell script?

Using arguments Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1 , $2 , and so on. The $0 will contain the script name.

How can we pass arguments to a script in Linux and access these arguments from within the 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.


1 Answers

By sourcing the second script with . /home/admin/script2.sh, you're effectively including it in the first script, so you get the command line arguments to the original script in $@. If you really want to call the other script with arguments, then do

/home/admin/script2.sh "$ARG1" "$ARG2" "$ARG3"

(make sure it's executable).

like image 106
Fred Foo Avatar answered Oct 06 '22 12:10

Fred Foo