Eugene Sirko
Eugene Sirko

Reputation: 25

.sh script will not let me loop through files

I am trying to print out my files on /var/www/ but for some reason I get this error: "temp.sh: line 3: FILES: command not found"

Code:

#loop through files FILES = /var/www/* for f in $FILES do echo "processing $f" done

I am running this from the home directory by command line like this sh script.sh (if that matters)

Upvotes: 0

Views: 61

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126278

To set a variable in sh, there cannot be any spaces before or after the = character. Change your code to

FILES=/var/www/*

However, this will have problems if any of the files in /var/www have spaces in their names, as they'll be split after variable substitution in your for line. So if there's a file like name with space, you'll get

processing /var/www/name
processing with
processing space

You can avoid that by putting the pattern directly in the for command, as pathname expansion occurs after word splitting:

for f in /var/www/*; do
    echo "processing $f"
done

and you'll get processing /var/www/name with space

Alternately, you can use a variable for the directory -- you just need to insure that the wildcards are in the for line to get the expansion/splitting in the correct order:

FILE_DIR=/var/www
for f in $FILE_DIR/*; do

Upvotes: 2

Related Questions