LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   How to use command xargs to run my custom program? (https://www.linuxquestions.org/questions/linux-software-2/how-to-use-command-xargs-to-run-my-custom-program-891439/)

915086731 07-13-2011 03:07 AM

How to use command xargs to run my custom program?
 
I want to list all files by command ls , then use command xargs to deal the results.
The result is the following:
Code:

[river@localhost a]$ ls
a.c  a.out  b.c  cscope.in.out  cscope.out  cscope.po.out  Makefile  tags
[river@localhost a]$ ./a.out  a.c
./a.out, a.c
[river@localhost a]$ ls | xargs ./a.out
./a.out, a.c
[river@localhost a]$

What's wrong, only the first file listed can be dealed.

The source code of a.out is :
Code:

#include <stdio.h>

int main( int argc , char* argv[] ) {
    printf("%s, %s\n", argv[0], argv [1]);
    return 0;
}

Can anyone help me ?
Thanks!

TobiSGD 07-13-2011 03:11 AM

The problem is not with xargs, but with your program. xrags gives the output of ls to your program, but the program prints out only the first two arguments argv[0] and argv[1].

915086731 07-13-2011 03:27 AM

Thanks!
I have thought the command xargs can spilt the result and then deal with every piece .
So I can just use command
Code:

./a.out  `ls`
, how can xargs be useful?

i92guboj 07-13-2011 04:17 AM

You can look at the xargs man page to find how to set the max number of arguments to dump on every iteration of the command. However what you should do is to modify your program to iterate through all the given arguments, in my opinion.

I also don't like using ls like that, it will give you trouble some day.

http://mywiki.wooledge.org/ParsingLs

MTK358 07-13-2011 07:01 AM

Do not parse the output of ls. It's meant for human reading, and parsing it could cause huge trouble, especially if filenames contain whitespace.

What's wrong with this:

Code:

./a.out *
???

915086731 07-15-2011 03:56 AM

Thanks for everyone!
I got it.

b0uncer 07-15-2011 04:01 AM

If you insist on working on the files one by one, why not just build a list of files using your friendly neighbourhood shell (which I assume to be Bash here; for other shells, see their documentation) and then loop on that list:

Code:

for i in *; do ./a.out "$i"; done
which is what you originally thought xargs would have done, if I understood you correctly (but still, do modify your program to handle multiple arguments, if it is suitable).

Edit: ha, now that I read the linked page in post #4, I noticed that the for loop was mentioned there as an option to ls :) Great.


All times are GMT -5. The time now is 05:11 PM.