Bash Grep Alias – Different Output When Using Alias

aliasbashgrep

I have a command set as an alias like this:

alias badalarm="cat ~/sagLogs/* | grep -I 'failed to generate expected' | awk '{print $4}' | sort | uniq | tee /dev/tty | wc -l" 

It gives me this output:

$ badalarm
alg-t1sg0103
alg-t1sg0104
all-t1sg0006
all-t1sg0009
input)
5

However, if I run the commands from the CLI directly I get:

$ cat ~/sagLogs/* | grep -I 'failed to generate expected' | awk '{print $4}' | sort | uniq | tee /dev/tty | wc -l
alg-t1sg0103
alg-t1sg0104
all-t1sg0006
all-t1sg0009
4

How come the alias version is picking up some other file? When I use
cat ~/sagLogs/* | grep 'failed to generate expected'

I get this output:

[...]
Apr:09:09:31:01:         >>>1 on all-t1sg0009 failed to generate expected 134
Apr:09:09:31:01:         >>>2 on all-t1sg0009 failed to generate expected 107
Apr:09:09:31:01:         >>>2 on all-t1sg0009 failed to generate expected 108
Apr:10:08:00:35:         >>>1 on all-t1sg0009 failed to generate expected 133
Apr:10:08:00:35:         >>>1 on all-t1sg0009 failed to generate expected 107
Binary file (standard input) matches

How can I omit the 'standard input' file from my alias?

Best Answer

When you declare your alias, the $4 in the awk command is within double quotes (since the whole alias string is within double quotes). This means that it will be expanded by the shell, most likely to an empty string. It does not matter that the $4 is within single quotes within the double quotes.

Instead, consider using a shell function,

badalarm () {
    cat "$HOME"/sagLogs/* |
    grep -I 'failed to generate expected' |
    awk '{ print $4 }' | sort -u |
    tee | wc -l
}

This avoids any quoting issues.

I also shorten the pipeline somewhat and replaced outputting directly to the TTY with outputting to standard output instead (so that both the output of tee and wc -l are sent there).

Related Question