在 Bash 中仅使用 ls 列出目录?

此命令列出当前路径中的目录: ls -d */

*/模式到底是做什么的?

以及如何在上述命令中给出绝对路径(例如ls -d /home/alice/Documents )以仅列出该路径中的目录?

答案

*/是与当前目录中所有子目录匹配的模式( *将与所有文件子目录匹配; /将其限制为目录)。同样,要列出 / home / alice / Documents 下的所有子目录,请使用ls -d /home/alice/Documents/*/

cs/ draft/ files/ hacks/ masters/ static/  
cs/code/ files/images/ static/images/ static/stylesheets/
cs/     files/      masters/  
draft/  hacks/      static/
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
cs  
draft  
files  
hacks  
masters  
static
cs/  
draft/  
files/  
hacks/  
masters/  
static/
ls -d */ | cut -f1 -d'/'
find /home/alice/Documents -maxdepth 1 -type d
find /home/alice/Documents -type d
echo */
echo ./*/              ### avoid misinterpreting filenames like "-e dir"
mkdir test-dir; cd test-dir
mkdir {cs,files,masters,draft,static}   # safe directories.
mkdir {*,-,--,-v\ var,-h,-n,dir\ with\ spaces}  # some a bit less secure.
touch -- 'file with spaces' '-a' '-l' 'filename'    # and some files:
./--/ ./-/ ./*/ ./cs/ ./dir with spaces/ ./draft/ ./files/ ./-h/
./masters/ ./-n/ ./static/ ./-v var/
ls -d */
ls -d ./*/                     ### more reliable BSD ls
ls -d -- */                    ### more reliable GNU ls
$ printf "%s\n" */        ### Correct even with "-", spaces or newlines.
$ set -- */; printf "%s\n" "${@%/}"        ### Correct with spaces and newlines.
$ for i in $(ls -d */); do echo ${i%%/}; done
$ listdirs(){ set -- */; printf "%s\n" "${@%/}"; }
$ listdirs
--
-
*
cs
dir with spaces
draft
files
-h
masters
-n
static
-v var
$ tree
.
├── config.dat
├── data
│   ├── data1.bin
│   ├── data2.inf
│   └── sql
|   │   └── data3.sql
├── images
│   ├── background.jpg
│   ├── icon.gif
│   └── logo.jpg
├── program.exe
└── readme.txt
$ tree -dfi
.
./data
./data/sql
./images
-d     List directories only.
-f     Prints the full path prefix for each file.
-i     Makes tree not print the indentation lines, useful when used in conjunction with the -f option.
$ tree -dfi "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/data/sql
/home/alice/Documents/images
$ tree -dfi -L 1 "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/images
[prompt]$ ls -d */    
app//  cgi-bin//  lib//        pub//
alias lsd='ls -ld */'
ls -l | grep '^d'
ls -1p | grep '/$'
ls -1p | grep '/$' | sed 's/\/$//'
ls -1p | grep -P '(?=/$)'
ls -l | grep "^d" | awk -F" " '{print $9}'
ls -Al | grep "^d" | awk -F" " '{print $9}'
find -maxdepth 1 -type d | awk -F"./" '{print $2}'