Search code examples
linuxshellksh

Why does find command in if return "paths must precede expression" error?


Below is my ksh script. I am getting paths must precede expression error for the first if test condition. To check if I have the correct syntax for if..find, I added the second section and I correctly get the message pass 2 - found files.

I also verified that the below find command runs successfully and returns me the correct files that I want. I tried putting double quotes around PAY*.txt and also backslash before asterisk 'PAY*.txt' but no luck.

find -iname 'PAY*.txt' -newermt '2021/04/22 00:00' ! -newermt '2021/04/22 23:59' -print

I am guessing the issue might be with the p_date1 and p_date2 being passed but again I don't know enough and unable to resolve it. Any help will be greatly appreciated.

#!/bin/ksh

p_date1='2021/04/22 00:00'
p_date2='2021/04/22 23:59'

if test -n "$(find -iname 'PAY*.txt' -newermt $p_date1 ! -newermt $p_date2 -print)";
then
  echo 'Files exist to upload'
else
  echo 'No Payment files exist to upload'
fi

if test -n "$(find -iname 'PAY*.txt' -ls)";
then
  echo 'pass 2 - found files'
else
  echo 'pass 2 - no files'
fi

Thanks.


Solution

  • The problem are the date variables - and if you had read find's output correctly you would have noticed that, too.

    if test -n "$(find . -iname 'PAY*.txt' -newermt "$p_date1" ! -newermt "$p_date2" -print)";
    

    Note the double quotes around the variable names.