Bash – Loop through files excluding directories

bashfor

I need my script to do something to every file in the current directory excluding any sub-directories.

For example, in the current path, there are 5 files, but 1 of them is a folder (a sub-directory).
My script should activate a command given as arguments when running said script. I.e. "bash script wc -w" should give the word count of each file in the current directory, but not any of the folders, so that the output never has any of the "/sub/dir: Is a directory" lines.

My current script:

#!/bin/bash
dir=`pwd`
for file in $dir/*
do
    $* $file
done

I just need to exclude directories for the loop, but I don`t know how.

Best Answer

#!/bin/bash -

for file in "$dir"/*
do
  if [ ! -d "$file" ]; then
      "$@" "$file"
  fi
done

Note that it also excludes files that are of type symlink and where the symlink resolves to a file of type directory (which is probably what you want).

Alternative (from comments), check only for files:

for file in "$dir"/*
do
  if [ -f "$file" ]; then
      "$@" "$file"
  fi
done
Related Question