Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep: invalid context length argument

Tags:

grep

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?

like image 299
Ricky Robinson Avatar asked May 15 '26 18:05

Ricky Robinson


1 Answers

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.

like image 76
Todd A. Jacobs Avatar answered May 19 '26 04:05

Todd A. Jacobs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!