Do not show results if directory is empty using Ba

2019-02-25 03:27发布

For example, try following command in an empty directory:

$ for i in *; do echo $i; done
*

Is there a way to suppress the printout of *?

标签: bash shell
3条回答
聊天终结者
2楼-- · 2019-02-25 03:35

To avoid the *, you can try something like

for i in `ls`; do echo $i; done

Tried now on an empty directory, no output given...

查看更多
别忘想泡老子
3楼-- · 2019-02-25 03:47

Set nullglob

shopt -s nullglob
for i in *; do echo "$i"; done
查看更多
Juvenile、少年°
4楼-- · 2019-02-25 03:49

Basic idea is use ls command, but if filename has space, ls will split file name by space. In order to handle space in filename, you can do like this:

ls|while read i; do echo $i; done

Aleks-Daniel Jakimenko said "Do not parse ls". Which is good, so how about this if we don't want to change nullglob:

for i in *; do  [ -e "$i" ] && echo $i; done
查看更多
登录 后发表回答