-1

This is my script, I want to find a pattern in a file. I know the exit status of grep -q '<Pattern>' '<file>' && echo $? is 0 if pattern is found. But I am getting if: Expression Syntax error.

 if ( (grep -q '<Pattern>' '<file>' && echo $?)==0  ) then
 echo "Pattern found"
 else
 echo "Pattern not found"
 endif
sid
  • 113
  • 1
  • 9
  • 2
    I don't know tcsh, but in bash and POSIX sh, you'd just do `if grep -q '' ''; then`. – Benjamin W. Aug 28 '18 at 14:44
  • I'd do that in `tcsh` as well: `sh -c 'if grep -q "" ""; then ... '` :) – chepner Aug 28 '18 at 15:27
  • 1
    BTW, the `shell` tag is generally focused on POSIX-family shells; better to stick to `csh` and `tcsh` tags here, to avoid pulling in a bunch of folks who consider any use of csh [severely](http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/) [misguided](http://www.grymoire.com/unix/CshTop10.txt). – Charles Duffy Aug 28 '18 at 16:35

1 Answers1

2

I think you want this:

if ( { grep -q '<Pattern>' '<file>' } ) then
 echo "Pattern found"
else
 echo "Pattern not found"
endif

Note the curly braces around command and the spaces between braces and command.

See the man tcsh, Expressions:

Command exit status

Commands can be executed in expressions and their exit status returned by enclosing them in braces ('{}'). Remember that the braces should be separated from the words of the command by spaces.

uzsolt
  • 5,832
  • 2
  • 20
  • 32