Listing only directories in UNIX

前端 未结 20 887
青春惊慌失措
青春惊慌失措 2020-12-12 09:40

I want to list only the directories in specified path (ls doesn\'t have such option). Also, can this be done with a single line command?

20条回答
  •  孤城傲影
    2020-12-12 10:22

    In bash:

    ls -d */
    

    Will list all directories

    ls -ld */
    

    will list all directories in long form

    ls -ld */ .*/
    

    will list all directories, including hidden directories, in long form.


    I have recently switched to zsh (MacOS Catalina), and found that:

    ls -ld */ .*/
    

    no longer works if the current directory contains no hidden directories.

    zsh: no matches found: .*/
    

    It will print the above error, but also will fail to print any directories.

    ls -ld *(/) .*(/)
    

    Also fails in the same way.

    So far I have found that this:

    ls -ld */;ls -ld .*/
    

    is a decent workaround. The ; is a command separator. But it means that if there are no hidden directories, it will list directories, and still print the error for no hidden directories:

    foo
    bar
    zsh: no matches found: .*/
    

    ls is the shell command for list contents of current directory
    -l is the flag to specify that you want to list in Longford (one item per line + a bunch of other cool information)
    -d is the flag to list all directories "as files" and not recursively
    */ is the argument 'list all files ending in a slash'
    * is a simple regex command for "anything", so */ is asking the shell to list "anything ending in '/'"

    See man ls for more information.


    I put this:

    alias lad="ls -ld */;ls -ld .*/"

    in my .zshrc, and it seems to work fine.

    NOTE: I've also discovered that

    ls -ld .*/ 2> /dev/null

    doesn't work, as it still prints sterr to the terminal. I'll update my answer if/when I find a solution.

提交回复
热议问题