Jon Griffith
Jon Griffith

Reputation: 183

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

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?

Upvotes: 0

Views: 54

Answers (2)

user1934428
user1934428

Reputation: 22225

As Shawn said in his comment, this would be easier in zsh, but in bash, you would do a

for f in /path/to/files/*
do
  if [[ ! -d $f ]]
  then
    thing
  fi
done

Note that this would skip files where the name starts with a period; but this was also present in your own attempt, and I assume that this is what you want.

Upvotes: 1

sidcoder
sidcoder

Reputation: 460

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

Upvotes: 0

Related Questions