Anthony Miller
Anthony Miller

Reputation: 15921

Nesting a for loop in an if else statement

if [ ! -f ./* ]; then
  for files in $(find . -maxdepth 1 -type f); do
    echo $files
else
  echo Nothing here
fi

Returns

syntax error near unexpected token `else'

New to this. Can anyone point me to what I did wrong?

Upvotes: 1

Views: 15281

Answers (3)

jordanm
jordanm

Reputation: 34924

The reason you get a syntax error is because you are not ending the loop with the "done" statement. You should be using a while loop, instead of a for loop in this case, as the for loop will break if any of the filenames contain spaces or newlines.

Also, the test command you have issued will also give a syntax error if the glob expands to multiple files.

$ [ ! -f ./* ]
bash: [: too many arguments

Here is a better way to check if the directory contains any files:

files=(./*) # populate an array with file or directory names
hasfile=false
for file in "${files[@]}"; do
   if [[ -f $file ]]; then
      hasfile=true
      break
   fi
done

if $hasfile; then
   while read -r file; do
      echo "$file"
   done < <(find . -maxdepth 1 -type f)
fi

Also, you could simply replace the while loop with find -print if you have GNU find:

if $hasfile; then
   find . -maxdepth 1 -type f -print
fi

Upvotes: 3

Roger Lindsj&#246;
Roger Lindsj&#246;

Reputation: 11543

The syntax for "for" is

for: for NAME [in WORDS ... ;] do COMMANDS; done

You are missing the "done"

Try

if [ ! -f ./* ]; then
  for files in $(find . -maxdepth 1 -type f); do
    echo $files
  done
else
  echo Nothing here
fi

BTW, did you mean echo with lowercase rather than ECHO?

Upvotes: 0

Mischa Arefiev
Mischa Arefiev

Reputation: 5417

You forgot done!

if [ ! -f ./* ]; then
  for files in $(find . -maxdepth 1 -type f); do
    echo $files
  done
else
  echo Nothing here
fi

Upvotes: 5

Related Questions