Search code examples
bashrm

Bash - to pass to rm a filename which is in a variable, but with ! option


the command

rm  !("$filename")

does not work, because it is syntactically incorrect.

I want to remove other files in a directory but that one specified in the $filename variable.

Actually, the bash script is this:

#!/bin/bash

filename="$(ls -t | grep radar_ | head -n 1)"
echo "${filename}"
rm  !("$filename")

How can I do that?


Solution

  • You could try something like :

    DIR="/path_to_your_dir"
    for file in "${DIR}"/*; do 
      [[ $file = "${filename}" ]] || rm "${file}"
    done
    

    Or something like :

    DIR="/path_to_your_dir"
    ls -1 "${DIR}"|grep -v "${filename}"|xargs -I{} rm {}
    

    Or something like :

     find "${DIR}" ! -name "${filename}" -exec rm {} \;
     find "${DIR}" ! -name "${filename}" -a -type f -exec rm {} \; # apply the rm only on files (not on the directories for example)
    

    Personally I'd choose the find solution to do that kind of tasks (searching and doing operation on some files).