0

I'm using a bash shell script to delete certain files in directory using the below script

#!/bin/bash
path=$1
for filename in $path/*; do
    if [ -d "$filename" ]; then
        echo $filename
        rm $filename/*statssys*
    fi
done

In other words, it is looping one through all directories one level deep inside my specified path and removing any files that have statssys in the name. The problem is that the file paths retrieved in $filename contain numerical endings like file_path[8] or file_path[9]. The square brackets have to be escaped before the rm command works which I do not know how to do as they are hidden inside the $filename variable.

Any help appreciated.

1

In Bash scripts there are many pitfalls that a casual programmer may fall into.

One rule is to double quote every parameter expansion which is your main problem. Some other rules include avoid echo to output arbitrary data and use -- to separate options from other arguments to guard against arguments that happen to start with - but should not be taken as options.

In your example, you can change your script to something like:

#!/bin/bash --
path="$1"
for filename in "$path"/*; do
    if [ -d "$filename" ]; then
        printf '%s\n' "$filename"
        rm -- "$filename"/*statssys*
    fi
done

For more detailed explanation I strongly advise you to read Bash Pitfalls.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.