Why does ls give different output when piped

前端 未结 3 1453
青春惊慌失措
青春惊慌失措 2020-12-02 01:41

Printing to terminal directly:

$ ls
a.out  avg.c  avg.h

Piping to cat

$ ls | cat
a.out
avg.c
avg.h
         


        
3条回答
  •  感动是毒
    2020-12-02 02:17

    So that each line is one entry only, allowing the command the output is piped to to work as would likely be expected. For example (given your ls output), the following would probably not be what you want:

    $ ls | sort -r
    a.out  avg.c  avg.h
    

    But because sort didn't know there was more than one item per line, it couldn't do anything. Compare this to what actually occurs:

    $ ls | sort -r
    avg.h
    avg.c
    a.out
    

    You can achieve the (unexpected) first behavior by passing -C to ls.

提交回复
热议问题