Home > Net >  Bash script - how to apply condition only to file and not to folder?
Bash script - how to apply condition only to file and not to folder?

Time:03-16

I have this line of code in a bash script:

  for file in "$Path"/*;

  do
    unpack $file
  done
fi

unpack is the function that will run on the file.

Now I want it to run only on files - on folder.

How can this be done?

CodePudding user response:

This works even if the filenames have whitespace or glob characters in them:

for file in "$Path"/*
do
  if test -f "$file"
  then
    unpack "$file"
  fi
done

If you really are just running one command on the files, you can use this shorthand:

test -f "$file" && unpack "$file"

CodePudding user response:

You can use the find command to find files or folders with specific properties. The -type f argument means it will only return files, not folders.

Try something like this for the first line of your script:

for file in $(find "$Path" -type f)

Also note that the fi at the end of your script is incorrect because there is no corresponding if statement. And I'm not really sure what you mean by "files - on folder": maybe you had a typo.

  • Related