Ls: Display directory name when only one matches pattern

ls

When using ls to display files matching a pattern, it displays the directory names with contents if there are multiple matches, but if there is only one match, it omits the directory name. Here is an example:

example % ls
bar     barbados    foo

example % ls b*
bar:
1   2

barbados:
1   2

example % ls f*
1   2

In the example, requesting all files starting with b* matches two directories, and the output shows the names of both directories and their contents.

When I request f* the output shows a the single matching directory's contents, but omits the directory name.

How can I configure ls to display the name of the matching directory in the case that it matches only a single directory?

Best Answer

Possible workaround might be a wrapper function:

dls() {
    if [ "$#" -eq 1 ] && [ -d "$1" ]; then
        printf '%s:\n' "$1"
    fi
    ls -- "$@"
}
  • The above function won't accept any options to be passed as arguments
  • It simply checks if:
    1. there is only a single argument
    2. the argument is a directory

If those two conditions are true, print the name of the directory before listing its contents.


% dls f*
foo:
1   2

With some printf implementations, you can replace the %s with %q for the directory name to be quoted in a similar fashion as recent versions of GNU ls do when it contains blanks or other special characters.