Listing only directories using ls in Bash? – Dev

The best answers to the question “Listing only directories using ls in Bash?” in the category Dev.

QUESTION:

This command lists directories in the current path: ls -d */

What exactly does the pattern */ do?

And how can we give the absolute path in the above command (e.g. ls -d /home/alice/Documents) for listing only directories in that path?

ANSWER:

Four ways to get this done, each with a different output format

1. Using echo

Example: echo */, echo */*/
Here is what I got:

cs/ draft/ files/ hacks/ masters/ static/  
cs/code/ files/images/ static/images/ static/stylesheets/  

2. Using ls only

Example: ls -d */
Here is exactly what I got:

cs/     files/      masters/  
draft/  hacks/      static/  

Or as list (with detail info): ls -dl */

3. Using ls and grep

Example: ls -l | grep "^d"
Here is what I got:

drwxr-xr-x  24 h  staff     816 Jun  8 10:55 cs  
drwxr-xr-x   6 h  staff     204 Jun  8 10:55 draft  
drwxr-xr-x   9 h  staff     306 Jun  8 10:55 files  
drwxr-xr-x   2 h  staff      68 Jun  9 13:19 hacks  
drwxr-xr-x   6 h  staff     204 Jun  8 10:55 masters  
drwxr-xr-x   4 h  staff     136 Jun  8 10:55 static  

4. Bash Script (Not recommended for filename containing spaces)

Example: for i in $(ls -d */); do echo ${i%%/}; done
Here is what I got:

cs  
draft  
files  
hacks  
masters  
static

If you like to have “https://stackoverflow.com/” as ending character, the command will be: for i in $(ls -d */); do echo ${i}; done

cs/  
draft/  
files/  
hacks/  
masters/  
static/

ANSWER:

*/ is a pattern that matches all of the subdirectories in the current directory (* would match all files and subdirectories; the / restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use ls -d /home/alice/Documents/*/

ANSWER:

For all folders without subfolders:

find /home/alice/Documents -maxdepth 1 -type d

For all folders with subfolders:

find /home/alice/Documents -type d

ANSWER:

I use:

ls -d */ | cut -f1 -d"https://stackoverflow.com/"

This creates a single column without a trailing slash – useful in scripts.