我想只列出指定路径中的目录(ls没有这样的选项)。 另外,这可以用单行命令完成吗?


当前回答

既然有几十种方法可以做到这一点,下面是另一种方法:

tree -d -L 1 -i --noreport

- d:目录 -L:树的深度(因此1是我们的工作目录) -i:不缩进,只打印名称 ——noreport:不报告树列表末尾的信息

其他回答

使用这个来获得目录列表

ls -d */ | sed -e "s/\///g"

试试这个:

find . -maxdepth 1 -type d

对于Bash脚本,我通常会尝试以一种不执行任何外部程序的方式来执行(grep, sed, ls,…)

for i in * ; do 
  if [[ -d "$i" ]] ; then
    echo "$i" 
  fi
done 

或者作为一条紧凑的直线

for i in * ; do [[ -d "$i" ]] && echo "$i" ; done 

如果我需要重用目录列表,我通常会把它放在一个数组中:

DIRS=() ; for i in * ; do [[ -d "$i" ]] && DIRS+=("$i") ; done 

然后使用"${DIRS[*]}"或"${DIRS[@]}"展开数组,如

for dir in "${DIRS[@]}" ; do 
   echo "Do something with directory $dir"
done

这种方法的另一个好处是它非常健壮。它可以处理目录名称中的空格和换行符。

如果我有这个目录:

ls -l

lrwxrwxrwx  1 nagios nagios     11 août   2 18:46 conf_nagios -> /etc/icinga
-rw-------  1 nagios nagios 724930 août  15 21:00 dead.letter
-rw-r--r--  1 nagios nagios  12312 août  23 00:13 icinga.log
-rw-r--r--  1 nagios nagios   8323 août  23 00:12 icinga.log.gz
drwxr-xr-x  2 nagios nagios   4096 août  23 16:36 tmp

要获取所有目录,使用-L解析链接:

ls -lL | grep '^d'

drwxr-xr-x 5 nagios nagios   4096 août  15 21:22 conf_nagios
drwxr-xr-x 2 nagios nagios   4096 août  23 16:41 tmp

没有- l:

Ls -l | grep '^d'

drwxr-xr-x 2 nagios nagios   4096 août  23 16:41 tmp

Conf_nagios目录缺失。

我发现在我面前有很多好的答案。但我想添加一个命令,我们已经使用它几次,所以很容易列出所有的目录较少的努力:

cd

(注意:cd后面有空格),按tab键两次,它将只列出当前工作目录下的所有目录。希望这是容易使用的。如果有任何问题请让我知道。谢谢。