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

for filename in $path/*; do
    if [ -d "$filename" ]; then
        echo $filename
        rm $filename/*statssys*

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 Answer 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 --
for filename in "$path"/*; do
    if [ -d "$filename" ]; then
        printf '%s\n' "$filename"
        rm -- "$filename"/*statssys*

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .