Shell – Pass multiple command line arguments to an executable with text files

command lineshell-script

I have a C executable that takes in 4 command line arguments.

program <arg1> <arg2> <arg3> <arg4>

I'd like to create a shell script that continually runs the executable with arguments supplied by text files. The idea would be something like this:

./program "$(< arg1.txt)" "$(< arg2.txt)" "$(< arg3.txt)" "$(< arg4.txt)"

Where the arguments supplied for run n would be on line n of each of the files. When I tried doing this, the printf() calls were interfering with each other or some other funny business was going on. I would also be open to a script that takes only one file where the arguments are delimited in some way.

Best Answer

while 
  IFS= read -r a1 <&3 &&
    IFS= read -r a2 <&4 &&
    IFS= read -r a3 <&5 &&
    IFS= read -r a4 <&6
do
  ./program "$a1" "$a2" "$a3" "$a4" 3<&- 4<&- 5<&- 6<&-
done 3< arg1.txt 4< arg2.txt 5< arg3.txt 6< arg4.txt

That runs the loop until one of the files is exhausted. Replace the &&s with ||s to run it until all the files are exhausted instead (using empty arguments for shorter files).

With GNU xargs, you could also do:

paste -d '\n' arg[1-4].txt | xargs -n 4 -r -d '\n' ./program

(though beware ./program's stdin would then be /dev/null)

Related Question