tonix tonix - 25 days ago 8
Bash Question

How to execute a conditional grep based on a shell function argument?

I have the following function:

function long_command() {
cat $1 | grep -vE '[a-fA-F0-9]{5}' | \
cat -n | sed -e 's/ / /g' | \
sed -e 's/^ *//g' | \
sort -k 3,3 -k 1n,1n | \
uniq -f 2 | \
sed -e 's/^[0-9]\{1,\} //' | \
grep -Ev '^\s*PATTERN\s+' | \
cat -n
}


The first part of the command filters some stuff. In the last part of the command I would like to filter using
grep -Ev '^\s*PATTERN\s+'
only if the argument
$2
is set and equals let's say
VALUE
, before piping to the last
cat -n
. How can I do that?

This doesn't work:

function long_command() {
cat $1 | grep -vE '[a-fA-F0-9]{5}' | \
cat -n | sed -e 's/ / /g' | \
sed -e 's/^ *//g' | \
sort -k 3,3 -k 1n,1n | \
uniq -f 2 | \
sed -e 's/^[0-9]\{1,\} //' | \
if [ "$2" -eq "VALUE" ]; then grep -Ev '^\s*PATTERN\s+'; fi | \
cat -n
}


I get an error:

-bash: [: : integer expression expected


What't the correct way to use an if and pipe the result of the if to
cat -n
?

Thanks for the attention.

Answer

You cannot use if/else like shown in pipeline command since there is nothing in the else part. Also -eq requires integer comparison.

You can do it like this:

long_command() {
     grep -vE '[a-fA-F0-9]{5}' "$1" |
     cat -n |
     sed 's/    / /g' |
     sed 's/^  *//g' |
     sort -k 3,3 -k 1n,1n |
     uniq -f 2 |
     sed 's/^[0-9]\{1,\} //' |
     { [[ $2 == "VALUE" ]] && grep -Ev '^\s*PATTERN\s+' || cat; } | cat -n
}

I've removed a redundant cat at the start and there is no need to use \ after | to enter next command on new line.

After last pipe you can also use:

if [[ "$2" == "VALUE" ]]; then grep -Ev '^\s*PATTERN\s+'; else cat; fi
Comments