Search code examples
linuxxargs

Linux execute php file with arguments


I have .php takes three parameters. For example: ./execute.php 11 111 111 I have like list of data in text file with spacing. For example:

22 222 222
33 333 333
44 444 444

I was thinking for using xargs to pass in the arguements but its not working. here is my try

cat raw.txt | xargs -I % ./execute.php %0 %1 %2

doesn't work, any idea? thanks for the help


Solution

  • As per the following transcript, you are not handling the data correctly:

    pax> printf '2 22 222\n3 33 333\n4 44 444\n' | xargs -I % echo %0 %1 %2
    2 22 2220 2 22 2221 2 22 2222
    3 33 3330 3 33 3331 3 33 3332
    4 44 4440 4 44 4441 4 44 4442
    

    Each % is giving you the entire line, and the digit following the % is just tacked on to the end.

    To investigate, lets first create a fake processing file proc.sh (and chmod 700 it so we can run it easily):

    #!/usr/bin/env bash
    echo "$# '$1' '$2' '$3'"
    

    Even if you switch to xargs -I % ./proc.sh %, you'll find you get one argument with embedded spaces, not three individual arguments:

    pax> vi proc.sh ; printf '2 22 222\n3 33 333\n4 44 444\n' | xargs -I % ./proc.sh %
    1 '2 22 222' '' ''
    1 '3 33 333' '' ''
    1 '4 44 444' '' ''
    

    The easiest solution is probably to switch to a for read loop, something like:

    pax:~> printf '2 22 222\n3 33 333\n4 44 444\n' | while read p1 p2 p3 ; do ./proc.sh ${p1} ${p2} ${p3} ; done
    3 '2' '22' '222'
    3 '3' '33' '333'
    3 '4' '44' '444'
    

    You can see there the program is called with three arguments, you just have to adapt it to your own program:

    while read p1 p2 p3 ; do ./proc.sh ${p1} ${p2} ${p3} ; done < raw.txt