2

I'm trying to use a pipeline with cd and ls like this:

ls -l | cd /home/user/someDir

but nothing happens.

And I tried:

cd /home/user/someDir | ls -l

It seems that the cd command does nothing while the ls -l will work on the current directory.

The directory that I'm trying to open is valid.

Why is that? Is it possible to pipe commands with cd / ls? Didn't have any problem with other commands while using pipe.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
ic205
  • 131
  • 9

1 Answers1

11

cd takes no input and produces no output; as such, it does not make sense to use it in pipes (which take output from the left command and pass it as input to the right command).

Are you looking for ls -l ; cd /somewhere?

Another option (if you need to list the target directory) is:

cd /somewhere && ls -l

The '&&' here will prevent executing the second command (ls -l) if the target directory does not exist.

rkachach
  • 15,286
  • 6
  • 38
  • 62
Piskvor left the building
  • 89,423
  • 44
  • 175
  • 222
  • 4
    not sure how being a shell builtin command prevents from using pipes, e.g. `echo | read`. The key point here is no I/O for `cd`. – Andrey Dec 19 '15 at 08:01
  • 1
    The other key point is that running `cd` in a pipe runs it in a subshell; it does not affect the shell in which `ls` runs. – chepner Dec 19 '15 at 16:18