aboutsummaryrefslogtreecommitdiff
path: root/bash/bashrc.d/grep.bash
blob: 4560c4acc1d3260ae700eabdaca2e283f4c7d653 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Return appropriate options for grep
grepopts() {

    # Start with ignoring binary files
    local -a grepopts=(-I)

    # Snarf the output of `grep --help` into a variable
    local grephelp=$(grep --help 2>/dev/null)

    # If the --exclude option is available, exclude some VCS files
    if [[ $grephelp == *--exclude* ]] ; then
        for exclude_file in .gitignore .gitmodules ; do
            grepopts=("${grepopts[@]}" --exclude="$exclude_file")
        done
    fi

    # If the --exclude-dir option is available, exclude some VCS dirs
    if [[ $grephelp == *--exclude-dir* ]] ; then
        for exclude_dir in .cvs .git .hg .svn ; do
            grepopts=("${grepopts[@]}" --exclude-dir="$exclude_dir")
        done
    fi

    # If the --color option is available and we have a terminal that supports
    # at least eight colors, add --color=auto to the options
    local colors=$(tput colors 2>/dev/null)
    if [[ $grephelp == *--color* ]] && ((colors >= 8)) ; then
        grepopts=("${grepopts[@]}" --color=auto)
    fi

    # Print the options as a single string, space-delimited
    printf %s "${grepopts[*]}"
}

# Alias grep with those options
alias grep="grep $(grepopts)"

# Unset helper function
unset -f grepopts