我想只列出指定路径中的目录(ls没有这样的选项)。 另外,这可以用单行命令完成吗?
当前回答
您可以使用带有d开关的tree命令来实现这一点。
% tree -d tstdir
tstdir
|-- d1
| `-- d11
| `-- d111
`-- d2
`-- d21
`-- d211
6 directories
更多信息请参见人树。
其他回答
尝试使用ls -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
这种方法的另一个好处是它非常健壮。它可以处理目录名称中的空格和换行符。
试试这个:
find . -maxdepth 1 -type d
如果我有这个目录:
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目录缺失。
答案取决于您的shell。
以zsh为例,您可以执行以下操作:
echo *(/)
并且将显示当前工作目录中的所有目录。
更多信息请参见man zshexpn。
另一种方法是使用find(1),它应该适用于大多数Unix版本:
find . -maxdepth 1 -type d -print
find(1)有很多用途,所以我绝对推荐man find。