简体   繁体   中英

.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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM