Home > database >  How do I stop a for loop from looping over subdirectories?
How do I stop a for loop from looping over subdirectories?

Time:08-16

If in a #!/bin/bash script I have:

FILES="/path/to/files/" and that path contains files, and I insert this:

for f in $FILES
  do
    thing
  done

I get no result.

If I change FILES="/path/to/files/* then the loop runs and I get results. However, if part of the loop involves building a file folder structure beneath /path/to/files/, i.e. /path/to/files/folder1 folder2 etc., then on a subsequent run, those folders become part of the iteration.

So, is there a way to set the depth on the $FILES path so the for loop will only ever look at just that folder?

CodePudding user response:

Rather than using for f in $FILES I changed it to:

for f in $(find $FILES -maxdepth 1 -name "*.mp4")

Does anyone see any problems with this?

CodePudding user response:

The following script will only loop through files of the present folder, but will exclude subdirectories.

export selectedFiles=`ls -p | grep -v /`
for f in $selectedFiles
  do
    echo $f
  done

For any other folder, please store directory path in "theFolder", like shown below.

export theFolder="/home/user/thedirectory"
export selectedFiles=`ls $theFolder -p | grep -v /`
for f in $selectedFiles
  do
    echo $f
  done
  • Related