Can I script the program to run again with arguments from a text file?

My question is: I have a program written in C and running it. I use

./program.exe var_1 ... var_n

      

where var_i-th are both numeric values ​​and strings (used as filenames). I need the program to execute many times with different var_i-th values ​​and every time I had to call the above command.

Is there a way to prepare a .txt file (or something similar) like

  • ./program.exe var_1 ... var_n #configuration one
  • ...
  • ...
  • ./program.exe var_1 ... var_n #configuration N

and make the program work with that so that in one call I run all the configurations one by one?

thank

+3


source to share


3 answers


Create a text file ( foo.sh

for example) with this content, make it executable ( chmod u+x foo.sh

) and run it with ./foo.sh

:



#/bin/bash

/program.exe var_1 ... var_1 #configuration one
/program.exe var_1 ... var_2 #configuration two
/program.exe var_1 ... var_3 #configuration three
.
.
.
./program.exe var_1 ... var_n #configuration N

      

+3


source


To read each line in an array of strings and pass that array to a program, the methods described in BashFAQ # 1 can be used :

while read -r -a args; do
  ./program.exe "${args[@]}"
done <in.txt

      

will read arguments from in.txt

, expecting them to be separated by spaces. It will not follow quotes or escape sequences as syntactically significant.


The caveat is that if your file contains:

arg1 "argument two" 13

      



You'll get:

./program.exe 'arg1' '"argument' 'two"' '13'

      

... for just four arguments.


If you need quotes to be followed, we'll return to space with xargs

, but with one call per input line:

while read -r line; do
  xargs ./program.exe <<<"$line"
done <in.txt

      

+2


source


You can prepare a file with a custom parameter list for each line, for example:

var_1
var_2
var_1 var_3

      

Then a bash sentence like this will do the job:

cat myFile.txt | xargs ./program.exe

      

+1


source







All Articles