Bash - pass a script as an argument to another script

I cannot find a similar question about SO.

How to properly pass a bash script as an argument to another bash script.

For example, let's say I have two scripts, each of which can take several parameters, I want to pass one script as an argument to the other. Sort of:

./script1 (./script2 file1 file2) file3 

In the above example, script2 merges files file1 and file2 together, and echos a new file, however this is not relevant. I just want to know how I can pass script2 as a parameter, i.e. The correct syntax.

If this is not possible, any hint on how I can get around the problem would be appropriate.

+6
source share
2 answers

If you want to pass script2 as an argument to script1 to execute it inside the last, just enter the following code inside script1 and call script1 as follows:

 ./script1 "./script2 file1 file2" file3 # file4 file5 

Code inside script1 :

 $1 # here you're executing ./script2 file1 file2 shift another_command " $@ " # do anything else with the rest of params (file3) 

Or, if you know the number of script2 parameters and it has been fixed, you can also do it like this:

 ./script1 ./script2 file1 file2 file3 # file4 file5 

Code inside script1 :

 "$1" "$2" "$3" shift 3 another_command " $@ " # do anything else with the rest of params (file3) 
+3
source

If you want to pass the result of evaluating script2 as a parameter, use $() . Remember that you must quote it.

 ./script1 "$(./script2 file1 file2)" file3 
+5
source

Source: https://habr.com/ru/post/980502/


All Articles