6

I can't find a similar question on SO.

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

For example, let's say I have two scripts that can each accept a number of parameters, I want to pass one script as the argument of the other. Something like:

./script1 (./script2 file1 file2) file3

In the above example, script2 merges file1 and file2 together, and echos a new file, however that is irrelevant to the question. I just want to know how I can pass script2 as a parameter, i.e. the proper syntax.

If this is not possible, any hint as to how I may circumvent the issue would be appropriate.

8
  • How do you intend to use the script2, once you have "passed" it to script1? Commented Jan 4, 2015 at 20:45
  • At the moment, I'm not quite sure, the script1 I was using just iterates over all the contents of the parameters. But, I'm just interested in figuring out how I can pass the script as a parameter, because its not working for me. Commented Jan 4, 2015 at 20:48
  • 2
    It's still not clear to me what you're aiming to achieve, or what it really means to pass a script as a parameter. Parameters are just strings. Presumably you would like to run script2 passing the file names file1 and file2 at some point. Would it be sufficient to pass the result of this action? Commented Jan 4, 2015 at 21:11
  • What I was aiming to achieve was basically @Cameron Martin 's answer. Commented Jan 4, 2015 at 22:42
  • 2
    In that case, why did you accept the other answer? Commented Jan 4, 2015 at 22:43

2 Answers 2

5

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

./script1 "$(./script2 file1 file2)" file3
Sign up to request clarification or add additional context in comments.

1 Comment

Where evaluating means capturing the standard output as a single parameter.
4

If you want to pass script2 as an argument to script1 to execute it inside the last one, just put the following code inside script1 and call script1 like this:

./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 params to script2 and it is fixed, you can also do it as follows:

./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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.