Home > Net >  Pass output of a bash script as command line argument for another script
Pass output of a bash script as command line argument for another script

Time:12-09

Beginner in bash and makefiles here. I have a course where we need to create a makefile where each rule calls one of the already compiled programs. All of the compiled programs take a command line argument. As the arguments can be quite large and mostly consists of the same character in a row (for example AAAAAAA) I made a script that uses python to print the argument. Example:

#!/bin/bash
python -c 'print "A"*1000   "Q"*200'

I am wondering how to create the rule in the makefile so that the output of the above script will be passed as the command line argument. Essentially like this:

test:
    ./schoolprogram ./myprogram.sh

So when make test is executed then ./schoolprogram should be run with the argument 1000 A's followed by 200 Q's and not the literal string "./myprogram.sh".

CodePudding user response:

I don't know why you have a script that does nothing but invoke python; why not just run python directly?

In any event, this isn't really a makefile question it's mostly a shell question. When writing makefile recipes, the best way is to get the command you want to run working at your shell prompt, then take that same command (with one small tweak) and put it into your makefile.

In the shell, you can use either $(...) or backticks (an older style) to run a command and replace it with the output of that command. So you can run this:

$ ./schoolprogram $(./myprogram.sh)

or more easily:

$ ./schoolprogram $(python -c 'print "A"*1000   "Q"*200')

Now when you take a command and put it into a makefile recipe, the thing you have to remember is that the $ character is special to make, so if you want a $ to be passed to your command you have to escape it by doubling it, $$. So you'd write:

test:
        ./schoolprogram $$(./myprogram.sh)

or equivalently:

test:
        ./schoolprogram $$(python -c 'print "A"*1000   "Q"*200')
  • Related