Home > Enterprise >  Bash script delete all files except a selection of files
Bash script delete all files except a selection of files

Time:10-03

I have My bash script

#!/bin/bash
set -euxo pipefail
I_PATH=$(pwd)

shopt -s extglob 

for BASE in Adenina Citocina Guanina Timina
do
    cd ${BASE}
    rm !(*.psf|*.fdf|siesta|*.log)
    cd ${I_PATH}
done

I want it to delete all files except for the excluded files. The problem is that bash executes the command as follows

rm '!(*.psf|*.fdf|siesta|*.log)'

Then the script fails with

rm: cannot remove '!(*.psf|*.fdf|siesta|*.log)': No such file or directory

How can I prevent that the script to add ' ' to the command?

CodePudding user response:

use find command

for BASE in Adenina Citocina Guanina Timina
do
  find ${BASE} -type f ! -name "*.psf" ! -name "*.fdf" ! -name "siesta" ! -name"*.log" -delete
done

CodePudding user response:

Seems like there are no matches for your glob, resulting in the glob to be treated as a literal string. Enable nullglob to expand to nothing in case there are no matches

rm without any arguments may print an error, therefore we also use rm -f.

By the way: Globs work with brace expansions. You don't need the loop or cd.

shopt -s nullglob
shopt -s extglob
rm -f {Adenina,Citocina,Guanina,Timina}/!(*.psf|*.fdf|siesta|*.log)

Or {Aden,Citoc,Guan,Tim}ina/... if you want to shave off some bytes :)

  •  Tags:  
  • bash
  • Related