churchmice
churchmice

Reputation: 33

Can not pipe the output of echo command to ls

everyone, i found this strange problem ( maybe it is a feature ) this afternoon. In my current working directory, there are 5 files, namely a,b,c,d,e

If i issue the following command

echo "a" | ls -l

What I expect is only the detailed information of file a is listed. But from the output, the detailed information of file a,b,c,d,e are listed. It seems as if the command before the pipe is not working, eg, the following command will output exactly as if only ls -l is executed.

echo "whatever_you_type" | ls -l

I am confused, can anybody help to explain this issue? I know i can workaround this problem by using xargs, something like echo "a" | xargs ls -l But I want to know why.

Upvotes: 1

Views: 5421

Answers (2)

Holger Just
Holger Just

Reputation: 55718

When you pipe something into another process, it will be pushed into its STDIN stream. As ls does not read from stdin, it just ignores that. What you want is that the parameters are passed to the command line of ls. This can be achieved by using something like this:

my_file="a"
ls -l "$my_file"

Alternatively, you can use xargs which can be used to construct command line parameters from stdin input. In your case, you could use it like

echo "a" | xargs ls -l

It will execute an ls -l [filename] for each space-separated string of stdin input.

Upvotes: 9

Chris
Chris

Reputation: 3817

ls doesn't take input from stdin. xargs works because it invokes ls one or more times with arguments assembled from its input. An alternative way of achieving your example would be:

ls -l $(echo "a")

Just make sure you haven't got any filenames with spaces in.

Upvotes: 3

Related Questions