0

I'm trying to use process substitution with grep as follows:

#!/bin/bash
if [grep -c "*" <(cut -d"," -f5 input_q1.csv) ]
then
  echo "Yes";
else
  echo "No";
fi

But I'm getting the error:

line 2: [grep: command not found

What am I missing?

Mat
  • 202,337
  • 40
  • 393
  • 406
david watson
  • 99
  • 1
  • 10
  • Do you just want to `echo` a message depending on whether any `*` are found, or is your requirement more complex? – Tom Fenech Jan 24 '16 at 18:10

2 Answers2

1

[ ... ] is not part of the syntax of an if-statement; rather, [ (also called test) is a Bash built-in command that is very commonly used as the test-command in an if-statement.

In your case, your test-command is grep rather than [, so you would write:

if grep -c "*" <(cut -d"," -f5 input_q1.csv) ; then

Additionally, there's no real reason to use process substitution here. The overall result of a pipeline is the result of the final command in the pipeline; and grep supports reading from standard input. So you can write:

if cut -d"," -f5 input_q1.csv | grep -c "*" ; then

to support a wider range of systems.

(Incidentally, the quotation marks around the , don't do anything: -d"," means -d, means "-d,". If your goal is to "highlight" the delimiter, or set it off in some way, then it might make more sense to split it into a separate argument: -d ,. But that's a matter of preference.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Note that `grep "*"` is valid; it looks for the asterisk character. When there isn't anything for it to repeat zero or more times, the asterisk `*` stands for itself. Experiment with `grep '*' *.c` or `grep '* ' *.c` (assuming you have some C code with comments in it lying around). – Jonathan Leffler Jan 24 '16 at 17:44
  • @JonathanLeffler: Whoops, you're right. The spec [says](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03_03), "The shall be special except when used: • In a bracket expression • As the first character of an entire BRE (after an initial `'^'`, if any) • As the first character of a subexpression (after an initial `'^'`, if any); see BREs Matching Multiple Characters". Will fix, thanks! – ruakh Jan 24 '16 at 17:52
0
if cut -d"," -f5 input_q1.csv | grep -c "*"; then

... and you'll need to change * into a valid regex, because * most certainly isn't.

As I've explained in Why doesn't my if statement with backticks work properly?, if in shells takes a command.

[ is a way to invoke the test command -- it's NOT like the parentheses that if takes in other languages.

Community
  • 1
  • 1
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Note that `grep "*"` is valid; it looks for the asterisk character. When there isn't anything for it to repeat zero or more times, the asterisk `*` stands for itself. Experiment with `grep '*' *.c` or `grep '* ' *.c` (assuming you have some C code with comments in it lying around). – Jonathan Leffler Jan 24 '16 at 17:44