This question already has an answer here:
-
Why does ls give different output when piped
3 answers
When I execute the command ls
on my system, I get the following output:
System:~ user# ls
asd goodfile testfile this is a test file
However, when I pipe ls
to another program (such as cat
or gawk
), the following is output:
System:~ user# ls | cat
asd
goodfile
testfile
this is a test file
How do I get ls
to read the terminal size and output the same over a pipe as it does when printing directly to the terminal?
This question has been solved.
Since I'm using bash, I used the following to achieve the desired output:
System:~ user# ls -C -w "$(tput cols)" | cat
Use ls -C
to get columnar output again.
When ls
detects that its output isn't a terminal, it assumes that its output is being processed by some other process that wants to parse it, so it switches to -1
(one-entry-per-line) mode to make parsing easier. To make it format in columns as when it's outputting directly to a terminal, use -C
to switch back to column mode.
(Note, you may also have to use --color
if you care about color output, which is also normally suppressed by outputting to a pipe.)
Maybe -x
"list entries by lines instead of by columns" with possible -w
"assume screen width instead of current value" is what you need.
When the output goes to a pipe or non-terminal, the output format is like ls -1
. If you want the columnar output, use ls -C
instead.
The reason for the discrepancy is that it is usually easier to parse one-line-per-file output in shell scripts.
Since I'm using bash, I used the following to achieve the desired output:
System:~ user# ls -C -w "$(tput cols)" | cat