列出目录的基本脚本([:discover:unexpected operator)
我遇到运行列出目录的基本脚本的问题。
for item in * do if [ -d $item ] then echo $item fi done
结果:
- 列出所有系统文件夹
- 返回错误:for.sh:4:[:discover:意外操作符
- 列出我的所有文件夹,其名称以小写字符开头
我猜是-d发现初始小写字符的问题? 有人可以解释为什么会这样吗? 非常感谢提前。
某些目录/文件的名称中可能包含空格,这会导致您收到错误。 所以使用引号:
for item in * do if [ -d "$item" ] then echo "$item" fi done
如果你想按字母顺序排序使用
for item in * do if [ -d "$item" ] then echo "$item" fi done | sort
作为问题的一个示例,假设一个文件名为My File
。 如果你不使用引号你会得到(在bash扩展之后)
if [ -d My File ]
所以它就像“测试:是My
的目录吗?做File
”,但File
不是有效的test
操作符,因此错误。
以下回应当前目录中的所有目录(但不是虚线.git
,例如.git
)
#!/bin/bash find . -maxdepth 1 -mindepth 1 -type d | while read Directory; do echo "$Directory"; done