1

How can I check that the piped input matches a string exactly, preferably in a single line?

For example:

some command | <check that equals "foo" exactly>

Where it would return an exit code of 0 if it was an exact match.

I tried using grep, but I don't want an exit code of 0 if the input was "foobar" for example, only if it is exactly "foo"

brad
  • 930
  • 9
  • 22

3 Answers3

6

You can capture the output.

[[ $(some command) == "foo" ]]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
iBug
  • 35,554
  • 7
  • 89
  • 134
  • is it possible to do it on the one line? something like `some command | = "foo"`? – brad May 15 '18 at 15:31
  • @brad you may want to check out the [ternary operator in bash](https://stackoverflow.com/questions/3953645/ternary-operator-in-bash?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – JNevill May 15 '18 at 15:51
  • Could you provide an example of how that would look for my situation? It is still unclear to me after reading over that link – brad May 15 '18 at 16:02
  • @brad Just remove the `if then fi` and it's a one-liner. – iBug May 15 '18 at 16:10
  • `[[ $(printf 'foo\n') == "foo" ]] && echo an unexpected false positive` – Robin479 May 15 '18 at 16:37
2

Maybe something like this?

some command | cmp <(echo "expected output (plus a newline by echo)")

Here, cmp will compare the content of its standard input (because only one file is given) and that of the process substitution "file" <(…), which in this case is the command echo "…". Note, that echo will append a newline to its output, which can be suppressed with -n or by using printf instead.

You may also wish to --silence the output of cmp (see man cmp).

The diff command also operates in a similar fashion to cmp.

Another solution might be to use grep, but there is no ultimate way to make sure it "matches a string exactly", depending on newlines involved in some command output.

Robin479
  • 1,606
  • 15
  • 16
0

Solution using awk:

some command | awk '$0 == "foo" {print $0;}' | grep -q "" && echo "Match"
dtmland
  • 2,136
  • 4
  • 22
  • 45