Registered User
Registered User

Reputation: 5371

deleting files in a given subdirectory

I have a few subdirectories in a given folder, where a file d2.sh~ exists. I want to delete this file via following shell script, which, rather than writing in a .sh file I wrote on terminal, on one line. [Edit: been formatted properly here for clarity]

for i in `ls *`; do
    if [ -d $i ]; then
        cd $i
        rm d2.sh~
        cd ..
    fi
done

This did not give me any errors but it failed to delete d2.sh~ from the subdirectories. So I want to know what mistake I have made above?

Upvotes: 2

Views: 153

Answers (1)

SiegeX
SiegeX

Reputation: 140547

find /some/path -type f -name "d2.sh~" -delete

Your first mistake is trying to parse ls. See this link as to why.

Just use for i in *; do ....

If you need recursion then you need to look to find or if you have Bash 4.X you can do:

shopt -s globstar; for i in **/d2.sh~; do rm "$i"; done

Upvotes: 6

Related Questions