Ricky Robinson
Ricky Robinson

Reputation: 22933

grep: invalid context length argument

I want to check if an iptables rule exists (as seen here), but I get the following error:

$ sudo iptables-save | grep "-A OUTPUT -p tcp --tcp-flags  RST RST -j DROP"
grep:  OUTPUT -p tcp --tcp-flags  RST RST -j DROP: invalid context length argument

Perhaps I have to escape some characters?

Upvotes: 9

Views: 14024

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84423

Problem

grep "-A OUTPUT -p tcp --tcp-flags RST RST -j DROP"

With many shell tools, some arguments can be mistakenly interpreted as flags. Depending on your version of grep, the following will help grep understand that the "flags" aren't really flags, but are part of the expression you're searching for.

For example, consider:

$ echo "-Afoo" | grep  "-Afoo"
grep: Invalid argument

Solutions

Flags to Demarcate Expressions

  1. Use the special -- flag to indicate that no flags follow.

    grep -- "-A OUTPUT -p tcp --tcp-flags  RST RST -j DROP"
    
  2. Use the -e flag to explicitly identify the quoted text that follows as an expression to search for.

    grep -e "-A OUTPUT -p tcp --tcp-flags  RST RST -j DROP"
    

Examples of Solutions

This works for me either way with BSD grep. Consider the following examples:

$ echo "-Afoo" | grep -- "-Afoo"
-Afoo

$ echo "-Afoo" | grep -e "-Afoo"
-Afoo

While the examples are admitedly contrived, they illustrate the problem (and the solution) much more clearly, and can easily be tested even on systems that don't have iptables to use as input text.

Upvotes: 15

Related Questions