sansSpoon
sansSpoon

Reputation: 2185

Bash - loop over path as parameter

If I want to loop over a statically assigned directory I can do:

cd /path/to/directory
for file in *
do
    echo 'Found file' $file
done

If I wanted to pass the directory as an argument, then I could:

cd $1
for file in *
do
    echo 'Found file' $file
done

If I move the $1 argument into the loop, I get an error, because it's not an array:

for file in $1
do
    echo 'Found file' $file
done

Is there a better way to do this without having to cd into the directory first?

Upvotes: 0

Views: 829

Answers (2)

JawguyChooser
JawguyChooser

Reputation: 1926

@Gordon Davisson's answer should work. He's using what's called globbing to get the contents of whatever's in $1. Alternatively to the globbing, you could just use ls

for file in $(ls $1}); do
  echo "Found file ${file}"
done

You could use backtics:

for file in `ls $1`; do
  echo "Found file ${file}"
done

There's a lot of ways to make this work. If you want to only print things that are file (not subdirectories):

dir=$1
for file in $(ls $dir); do
  if [[ -f ${dir}/${file} ]]; then
    echo "File found ${file}"
  fi
do

Cheers!

Upvotes: -1

Gordon Davisson
Gordon Davisson

Reputation: 125788

If I understand right, you're trying to loop over the files in the directory specified by $1. In that case, you can do this:

for file in "$1"/*
do
    echo 'Found file' "$file"
done

Note that I've also enclosed all variable references in double-quotes. This is almost always a good idea, since it prevents misparsing if the variables contain spaces, tabs, wildcards, etc (all of which are legal in filenames). On the other hand, the * cannot be quoted, or it won't get expanded; so "$1"/* is half-quoted to get the right treatment.

Upvotes: 4

Related Questions