Bash – When the lines of a file or directory get too long, upgrade to ls list format

bashbashrccoreutils

Is there a way I can do this? For example if a gets a long name like:

i-have-names-that-are-too-long-to-describe/
i-have-names-that-are-too-long-to-describe-2/
i-have-names-that-are-too-long-to-descri-3/

Can I "upgrade" over from ls to ls -l given that I have a name of a file or directory that is longer than than say, 20 characters?

Is there a way to set up a bash function in my .bashrc to do this? I'll call the resulting function lls().

@tripleee asked:

Do you want ls -l when the input file name is long? Why? It will make the output longer, not shorter. What if you receive a mix of long and short filenames?

I want it more so that reading the long filenames are systematized to a list (and easier for me to digest and read going down a fixed column); for a mix of long and short filenames, I would default to the list format.

Best Answer

There's no builtin option in ls that does what you want. You'd have to parse the output then restart if "long" filenames are found, or do something like:

$ ls ??????????* >& /dev/null && ls -l || ls

(Put as many ? as your length limit. You can set that up as an alias.)

Why don't you simply use ls -1? (That's a one, not a lowercase L.) It always lists files in a single column. (Or pipe ls to more or less, which also goes to single column display.) Or use find with -maxdepth 1.

Related Question