dyno8426
dyno8426

Reputation: 1249

Bash script to remove all image files from a given directory

I am using the following shell-script to clean the after-effects of a python script that I am running:

echo "Cleaning up..."
# some other files removed here...
# removing some log files
if [ -f log_errors.txt ]; then
    rm log_errors.txt
fi
# removing all the generated image files
if [ -f IMG_* ]; then
    rm IMG_*
fi
# some more files removed here...
ls

But, on doing bash clean.sh, I am getting the following error:

Cleaning up...
clean.sh: line 11: [: too many arguments

Can someone please help me? Thanks in advance.

EDIT: Consider that there are no sub-folders within this directory.

Upvotes: 1

Views: 2045

Answers (4)

jokimina
jokimina

Reputation: 66

Sorry for my not precise answer before.

Follow code On centos 6.5 works. If run on current directory. with -maxdepth 1

find . -maxdepth 1 -name "IMG_*" -or -name "log_errors.txt" -exec rm -fv {} +

and you'd batter run

find . -maxdepth 1 -name "IMG_*" -or -name "log_errors.txt"

make sure before with -exec

or

  find . -maxdepth 1 -name "IMG_*" -or -name "log_errors.txt" | xargs  -I {} -t rm -fv {}

Thanks mklement0. you are nice man. (:

Upvotes: 1

Yous
Yous

Reputation: 728

If you want to check the existence of the files, you can use:

imgs=(IMG_*)
[ -f "${imgs[0]}" ] && rm "${imgs[@]}"

It works whether nullglob option is set or not, as ${imgs[0]} will be the pattern IMG_* if there is no such file.

If you set the option using shopt -s nullglob, you can check with (note the use of a subshell - (...) - to localize the effect of setting nullglob):

(shopt -s nullglob; imgs=(IMG_*)
[ ${#imgs[@]} -gt 0 ] && rm "${imgs[@]}")

Upvotes: -1

lewiatan
lewiatan

Reputation: 1176

You can try:

#!/bin/bash
for f in IMG_* ; do
    if [ -f "$f" ] ; then
        rm "$f"
    fi
done

This will iterate over all of files starting with IMG_ and run rm on them.

And this omit subfolders if they exist..

EDIT: Fixed due to comments

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74595

IMG_* is being expanded to the full list of files matching the pattern, so your test will end up being something like if [ -f IMG_1 IMG_2 IMG_3 ..., which is too many arguments!

If you always want to remove all the files matching the pattern, then just pass the -f argument to rm and lose the if:

rm -f IMG_*

This will remove everything it can and do nothing if no files were found.

Upvotes: 8

Related Questions