Fast algorithm to determine grep alias flags
This version tries whether grep supports all the flags together
and progressively checks older flags if the grep test fails.
This means only one grep call if all flags are supported, and
one additional call for every flag that's not supported, up to
a maximum of 3 calls.
Diff
1diff --git a/lib/grep.zsh b/lib/grep.zsh
2index df9146aa4b355e703020b183c2e4fed7f19bbbb8..933de2990eb7992932871d00e792cc45a2a1d21f 100644
3--- a/lib/grep.zsh
4+++ b/lib/grep.zsh
5@@ -4,37 +4,36 @@ if (( $#_grep_alias_cache )); then
6 source "$ZSH_CACHE_DIR"/grep_alias.zsh
7 else
8 # is x grep argument available?
9- grep-flag-available() {
10- echo | grep $1 "" >/dev/null 2>&1
11+ grep-flags-available() {
12+ echo | grep "$@" "" >/dev/null 2>&1
13 }
1415 GREP_OPTIONS=""
1617- # color grep results
18- if grep-flag-available --color=auto; then
19- GREP_OPTIONS+=" --color=auto"
20- fi
21-
22 # ignore these folders (if the necessary grep flags are available)
23 EXC_FOLDERS="{.bzr,CVS,.git,.hg,.svn,.idea,.tox}"
2425- if grep-flag-available --exclude-dir=.cvs; then
26- GREP_OPTIONS+=" --exclude-dir=$EXC_FOLDERS"
27- elif grep-flag-available --exclude=.cvs; then
28- GREP_OPTIONS+=" --exclude=$EXC_FOLDERS"
29+ if grep-flags-available --color=auto --exclude-dir=.cvs; then
30+ GREP_OPTIONS+="--color=auto --exclude-dir=$EXC_FOLDERS"
31+ elif grep-flags-available --color=auto --exclude=.cvs; then
32+ GREP_OPTIONS+="--color=auto --exclude=$EXC_FOLDERS"
33+ elif grep-flags-available --color=auto; then
34+ GREP_OPTIONS+="--color=auto"
35 fi
3637 {
38- # export grep, egrep and fgrep settings
39- echo alias grep="'grep $GREP_OPTIONS'"
40- echo alias egrep="'egrep $GREP_OPTIONS'"
41- echo alias fgrep="'fgrep $GREP_OPTIONS'"
42+ if [[ -n "$GREP_OPTIONS" ]]; then
43+ # export grep, egrep and fgrep settings
44+ echo alias grep="'grep $GREP_OPTIONS'"
45+ echo alias egrep="'egrep $GREP_OPTIONS'"
46+ echo alias fgrep="'fgrep $GREP_OPTIONS'"
47+ fi
48 } > "$ZSH_CACHE_DIR/grep_alias.zsh"
4950 source "$ZSH_CACHE_DIR/grep_alias.zsh"
5152 # clean up
53 unset GREP_OPTIONS EXC_FOLDERS
54- unfunction grep-flag-available
55+ unfunction grep-flags-available
56 fi
57 unset _grep_alias_cache