brad
brad

Reputation: 954

In bash check piped input matches string exactly

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"

Upvotes: 1

Views: 1366

Answers (3)

dtmland
dtmland

Reputation: 2216

Solution using awk:

some command | awk '$0 == "foo" {print $0;}' | grep -q "" && echo "Match"

Upvotes: 0

Robin479
Robin479

Reputation: 1686

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.

Upvotes: 2

iBug
iBug

Reputation: 37287

You can capture the output.

[[ $(some command) == "foo" ]]

Upvotes: 7

Related Questions