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.

  • 3
    Change all references of $filename to "$filename". For example, rm "$filename"/*statssys*.
    – FedKad
    Commented Feb 2, 2020 at 11:53
  • 4
  • Thanks @FedonKadifeli - that solved it! I had tried using double quotes before but I had put it around the whole statement instead of just the variable name which didn't work.
    – wrahman
    Commented Feb 2, 2020 at 12:04

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 .