Bash scripting, loop through files in folder fails

前端 未结 3 394
我在风中等你
我在风中等你 2020-12-16 14:29

I\'m looping through certain files (all files starting with MOVIE) in a folder with this bash script code:

for i in MY-FOLDER/MOVIE*
do

whi

相关标签:
3条回答
  • 2020-12-16 14:58

    With the nullglob option.

    $ shopt -s nullglob
    $ for i in zzz* ; do echo "$i" ; done
    $ 
    
    0 讨论(0)
  • 2020-12-16 15:11
    for file in MY-FOLDER/MOVIE*
    do
      # Skip if not a file
      test -f "$file" || continue
      # Now you know it's a file.
      ...
    done
    
    0 讨论(0)
  • 2020-12-16 15:12
    for i in $(find MY-FOLDER/MOVIE -type f); do
      echo $i
    done
    

    The find utility is one of the Swiss Army knives of linux. It starts at the directory you give it and finds all files in all subdirectories, according to the options you give it.

    -type f will find only regular files (not directories).

    As I wrote it, the command will find files in subdirectories as well; you can prevent that by adding -maxdepth 1


    Edit, 8 years later (thanks for the comment, @tadman!)

    You can avoid the loop altogether with

    find . -type f -exec echo "{}" \;
    

    This tells find to echo the name of each file by substituting its name for {}. The escaped semicolon is necessary to terminate the command that's passed to -exec.

    0 讨论(0)
提交回复
热议问题