2

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

test -e $FILE_PATH/$FILE_NAME

I have defined

FILE_NAME="ant"

Putting * after the FILE_NAME is not working out.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

3

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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 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
1

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     
z atef
  • 1,068