4

So I'm learning about pipes in bash and I found this pithy description:

A Unix pipe connects the STDOUT (standard output) file descriptor of the first process to the STDIN (standard input) of the second. What happens then is that when the first process writes to its STDOUT, that output can be immediately read (from STDIN) by the second process.

Source

Given this understanding, let's connect the STDOUT of printf to the STDIN of ls. For simplicity, print the parent directory (printf ..).

~/Desktop/pipes$ mkdir sub
~/Desktop/pipes$ ls
sub
~/Desktop/pipes$ cd sub
(no files)
~/Desktop/pipes/sub$ printf .. | ls
(no files)
~/Desktop/pipes/sub$ 

I want to be doing: ls .. but it seems that all I'm getting is ls. Why is this so? How can I ls the parent directory using pipes? Am I misunderstanding pipes?

Community
  • 1
  • 1
Kenny Worden
  • 4,335
  • 11
  • 35
  • 62

2 Answers2

3

Many programs don't read from stdin, not just ls. It is also possible that a program might not write to stdout either.

Here is a little experiment that might clarify things. Carry out these steps:

cat > file1
This is file1
^D

The ^D is you pressing <CTRL>+D, which is the default end-of-file. So, first we are calling the cat program and redirecting its stdout to file1. If you don't supply an input filename then it reads from stdin, so we type "This is file1".

Now do similar:

cat > file2
This is file2
^D

Now if you:

cat < file1

You get:

This is file1

what if you:

cat file1 | cat file2

or:

cat file2 < file1

Why? Because if you supply an input filename then the cat program does not read stdin, just like ls.

Now, how about:

cat - file1 < file2

By convention the - means a standard stream, stdin when reading or stdout when writing.

cdarke
  • 42,728
  • 8
  • 80
  • 84
2

The problem is ls does not read from stdin as you intended it to do. You need to use a tool that reads from the stdin like xargs and feed the read input to ls

printf "someSampleFolderOrFile" | xargs ls 

xargs man page,

xargs - build and execute command lines from standard input

Inian
  • 80,270
  • 14
  • 142
  • 161