'How to update my current directory while looping over it in shell script?

So, i loop over the command "ls"

    for d in $(ls)
    do
      echo $d
      rm -rf f1*.txt
    done

Before Loop: ls has [ f1.txt f2.txt f5.txt f11.txt f12.txt f7.txt ]

DESIRED OUTPUT: f1.txt f2.txt f5.txt f7.txt

ACTUAL OUTPUT: f1.txt f2.txt f5.txt f11.txt f12.txt f7.txt

After Loop: ls has [ f2.txt f5.txt f7.txt ]

It is not updating the command which is updating. Kindly help as I just started with Shell script and this is my first script for my job.



Solution 1:[1]

To do what you want, you need to keep an list of the files in a place that can be updated as you iterate over that list. One possible way of doing this is to have an associative array, keyed by filename, with the value of each element being a flag indicating whether , or not, it is active. For example:

#!/bin/bash

declare -A files=()

for file in *; do
  files["${file}"]=1
done

for file in "${!files[@]}"; do    # Iterate over the keys
  if [ files["${file}"] -eq 1 ]; then
    echo ${file}
    for f in f1*.txt; do
      rm "${f}"
      entries["${f}"]=0
    done
  fi
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Vickers