I have two programs ( Prog1.c
and Prog2.c
) written in C
and each of them take one command line argument.
Prog1.c
takes a file name as argument , reads content from file and outputs it on the STDOUT
(standard output) screen. Prog2.c
takes data as argument and does some operation. I want to redirect output of Prog1.c
to Prog2.c
as input.
I have tried following bash script which gives me error
#!/bin/bash
prog2 "`prog1 file.txt`"
I have also tried without quotes and in both cases, it gives me following error.
Prog2:: argument list too long.
To get the output of a command as a parameter for another command you can use backticks:
prog2 "`prog1 file.txt`"
or use $()
(I believe this is a more preferred way for bash):
prog2 "$(prog1 file.txt)"
If you want to use the STDOUT of prog1 as STDIN for prog2 use the | (pipe) operator:
prog1 | prog2
Note: When you want to use pipes, you need to modify the code of prog2, as it needs to read from STDIN instead of the command arguments ( argv
of the main()
function). See How to read a line from the console in C? for an example on how to do this.
PIPES!!!!!
On the command line (or in your script) do prog1 file.txt | prog2
prog1 file.txt | prog2
You must use backticks in both places before and after prog1
prog2 "`prog1 file.txt`"
When you get "argument list too long", you have reached the system limit for the command line. You must then find another way to send the data to prog2
. You can read from stdin
instead, and pipe the output of prog1 to prog2
prog1 file.txt | prog2
When you pipe the data from prog1 to prog2, you must change prog2 and read from stdin instead of using argv.
Example reading line by line:
char buf[1024];
while (fgets(buf, 1024, stdin)) {
/* process line in buf */
}
Example reading white space delimited words
char buf[1024];
while (scanf("%s", buf) != EOF) {
/* process word in buf */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.