-5

By using the command :

rm /file_path/*.csv

I can delete all csv files in the required folder.However if the directory is empty or there are no csv files I get the following error:

No such file or directory

How do I avoid this error?I have this logic in a script with certain downstream dependancies so throwing this error will cause the rest of my code to stop.Whats the best way in bash to delete files only if they exist in the directory?

chepner
  • 497,756
  • 71
  • 530
  • 681
user5347996
  • 1
  • 1
  • 4

3 Answers3

3

Another variant is to check if your folder is empty before to run your script:

find file_path/ -type d -empty

It returns the name of your folder if it is empty.

Or use the "-f" option with rm command if you want only avoid the error message:

Without:

rm -r file_path/*.csv
rm: cannot remove ‘file_path/*.csv’: No such file or directory

With:

rm -rf file_path/*.csv
choupit0
  • 49
  • 3
0

See Test whether a glob has any matches in bash for ways to check if /file_path/*.csv matches anything. However, even if you do such a test before running the rm command it may fail if the directory has a very large number of CSV files. See Argument list too long error for rm, cp, mv commands.

If you have a modern version of find, this is a reliable and efficient option:

find /file_path -maxdepth 1 -type f -name '*.csv' -delete
pjh
  • 6,388
  • 2
  • 16
  • 17
-2

You can do: [ -f /file_path/*.csv ] && rm /file_path/*.csv

Vaibhav
  • 484
  • 4
  • 7