Do not show results if directory is empty using Bash

后端 未结 3 1515
面向向阳花
面向向阳花 2021-01-20 22:20

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

相关标签:
3条回答
  • 2021-01-20 22:46

    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...

    0 讨论(0)
  • 2021-01-20 22:48

    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
    
    0 讨论(0)
  • 2021-01-20 23:10

    Set nullglob

    shopt -s nullglob
    for i in *; do echo "$i"; done
    
    0 讨论(0)
提交回复
热议问题