Terminal: grep command usage with ‘[‘ character as target, not function

terminal

Im using the grep command In a simple script, the problem however Is that the string which the grep command Is searching for includes a square bracket character: [.

After some research, i have found that the square bracket [ character is in fact used as a function for optimising the grep commands output through a process called "pipelining" (Although don't quote me on It as Im not sure).

My Question:

How do I search for a string with a '[' character in it without invoking a pipelining function within grep?

Elaboration:

The script Is searching a system log for the string su[. This Is my current malfunctioning command: tail -1 system.log | grep " su[", however It will not work due to the square bracket at the end, returning the error: grep: brackets ([ ]) not balanced.

Thanks In Advance.

Best Answer

Brackets should be escaped with \, because it's a special character. Your command will look like:

tail -1 system.log | grep " su\["

Special characters

From this site You can learn about special characters in bash.

What makes a character special? If it has a meaning beyond its literal meaning, a meta-meaning, then we refer to it as a special character. Along with commands and keywords, special characters are building blocks of Bash scripts.

\ is a special character and it could be used as:

[ ] test.

Test expression between [ ]. Note that [ is part of the shell builtin test (and a synonym for it), not a link to the external command /usr/bin/test.

[[ ]] test.

Test expression between [[ ]]. More flexible than the single-bracket [ ] test, this is a shell keyword.

[ ] array element.

In the context of an array, brackets set off the numbering of each element of that array. Array[1]=slot_1

echo ${Array[1]}

[ ] range of characters.

As part of a regular expression, brackets delineate a range of characters to match.

$[ ... ] integer expansion.

Evaluate integer expression between $[ ].