3

I am trying to use find in a shell script to count the number of files I have matching a wildcard pattern, then to get the name of the file if there is only one. But I'm having trouble passing the wildcard pattern through to backtick expansion.

FINDCMD="find . -iname *DATA*.txt"
DATACOUNT=$($FINDCMD | wc -l)

if [ $DATACOUNT -eq 1 ]
then
  use-data $($FINDCMD)
else
  echo bugger
fi

That doesn't work: the shell expands DATA.txt at the time of calling find. I want the asterisks to be passed to find.

If I make it

FINDCMD="find . -iname '*DATA*.txt'"

Then the shell doesn't expand the asteriks, but find gets the single-quotes and matches nothing.

blueshift
  • 6,742
  • 2
  • 39
  • 63

3 Answers3

1

Don't put your commands in a variable. What's wrong with just executing the command directly?

DATACOUNT=$(find . -iname "*DATA*.txt" | wc -l)
if [ $DATACOUNT -eq 1 ];then
    .....
fi

Edit:

if you wan to reuse the command, use a subroutine

myfind(){
    find . -iname "*DATA*.txt" | wc -l
}
kurumi
  • 25,121
  • 5
  • 44
  • 52
  • Because I want to reuse the same command to get the filename, if there is only one. Better for maintainability to have the command defined in only one place. But if I have to, I can do it like you suggest. There must be a better way.. – blueshift Apr 01 '11 at 08:38
1

Do BOTH of following:

  1. Use quotes in find command: FINDCMD="find . -iname \"*DATA*.txt\"" OR FINDCMD='find . -iname "*DATA*.txt"'
  2. Use following bash option: -f Disable pathname expansion. as follows set -f in the beginning of the script

That should do the trick. Not tested on your script though, but you should get the idea from this point.

Peter
  • 11
  • 1
-1

Switch the single and double quotes.

Try:

FINDCMD='find . -iname "*DATA*.txt"'
sureshvv
  • 4,234
  • 1
  • 26
  • 32