I need to test if a file starting with "ant" is present in the directory. If that is present, I need to delete that file. The command that I am using now is


I have defined


Putting * after the FILE_NAME is not working out.

closed as unclear what you're asking by sam, MelBurslan, Kusalananda, peterph, G-Man Says 'Reinstate Monica' Jul 28 '16 at 0:04

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


One portable way to remove such a file if only one exists:

set -- "${FILE_PATH}/${FILE_NAME}"*
[ $# -eq 1 -a -e "$1" ] && rm -- "$1"

It seems to me that if you don't care how many of these 'ant' files exist beforehand, but want them (all) gone when you're done, just:

rm -f "${FILE_PATH}/${FILE_NAME}"*

-- that way, if there were no such files, rm will (forced-quiet) not doing anything, but if there were (any -- 1 or more!) such files, rm will remove them.

  • 1
    In POSIX shells, set -- "${FILE_PATH}/${FILE_NAME}"*, will also set $# to 1 if there's no matching file as then the pattern is passed literally instead of the matching files. – Stéphane Chazelas Jul 27 '16 at 15:15
  • excellent catch; thank you, @StéphaneChazelas. I've updated the answer to additionally check for the existence of $1 and also safeguarded the "rm" with a -- delimiter. – Jeff Schaller Jul 27 '16 at 16:10

Here is another way of doing this:

-sh-4.1$ dir=$(pwd)  ; filename="ant" 

if (( $(shopt -s nullglob; set -- ${dir}/${filename}*;  echo $#) > 0 ));  then rm
${dir}/${filename}* ; fi    

shopt -s nullglob : will ensure noting is returned if the directory is empty.

set -- ${dir}/${filename}* : sets the positional param.

$# : returns the count of positional params. as the condition for excuting rm

as a one linear :

1$ dir=$(pwd) ; filename="ant" ;  if (( $(shopt -s nullglob; set -- ${dir}/${filename}*;  echo $#) > 0 )); then rm     ${dir}/${filename}* ; fi     

Not the answer you're looking for? Browse other questions tagged or ask your own question.