Linux – Make ls print it all on one line (like in terminal)

bashcommand-line-interfacelinuxshellunix

ls prints differently depending on whether the output is to a terminal or to something else.

e.g.:

$ ls .
file1  file2
$ ls . | head
file1
file2

Is there some way to make ls print out on one line as if it's to a terminal when it's not. There's a -C argument that sorta does that, but it will split it into several lines.

$ ls
file1  file10  file11  file12  file13  file14  file15  file16  file17  file18  file19 file2  file3  file4  file5  file6  file7  file8  file9
$ ls -C . | head
file1 file11 file13 file15 file17 file19 file3  file5  file7  file9
file10 file12 file14 file16 file18 file2 file4  file6  file8

The reason I want to do this is that I want to monitor the files in a directory that were changing quickly. I had constructed this simple command line:

while [[ true ]] ; do ls ; done | uniq

The uniq prevents it from spamming my terminal and only showing changes. However it was printing it all on differnet lines, which was making the uniq useless, and increasing the amount of noise. In theory one could use watch for this, but I wanted to see a file as soon as it appeared/disappeared.

This is the final solution:

while [[ true ]] ; do ls | tr '\n' ' ' ; done | uniq

Best Answer

i don't know of a switch which could do that, but you can pipe your output through tr to do it:

ls | tr "\n" " " | <whatever you like>