jonathan
jonathan

Reputation: 291

How does find and printf work when using pipes in bash scripting

Suppose I use the printf in the find command like this:

     find ./folder -printf "%f\n" | other command which uses the result of printf

in the other command part, I may be having a sort or something similar

what exactly does printf do in this case? where does it print the file names before the process in the part after "|" happens?

if I sort the filenames for example, it will first sort them, and then print them sorted on the monitor, but before that, how exactly does the part after | get the files unsorted in order to sort them? does the printf in this case give the filenames as input to the part after | and then the part after | prints the file names sorted in the output?

sorry for my english :(

Upvotes: 1

Views: 1486

Answers (2)

Ben Jackson
Ben Jackson

Reputation: 93880

Your shell calls pipe() which creates two file descriptors. Writing into one buffers data in the kernel which is available to be read by the other. Then it calls fork() to make a new process for the find command. After the fork() it closes stdout (always fd 1) and uses dup2() to copy one end of the pipe to stdout. Then it uses exec() to run find (replacing the copy of the shell in the subprocess with find). When find runs it just prints to stdout as normal, but it has inherited it from the shell which made it the pipe. Meanwhile the shell is doing the same thing for other command... with stdin so that it is created with fd 0 connected to the other end of the pipe.

Upvotes: 2

tripleee
tripleee

Reputation: 189749

Yes, that is how pipes work. The output from the first process is the input to the second. In terms of implementation, the shell creates a socket which receives input from the first process from its standard output, and writes output to the second process on its standard input.

... You should perhaps read an introduction to Unix shell programming if you have this type of questions.

Upvotes: 0

Related Questions