1

I came up with this snippet to simplify use of history and prevent flooding of the scroll buffer:

h() {
    if [ $# -eq 1 ]; then
        history | grep $1 | tail -n $(expr $(tput lines) - 1)
    else
        history | tail -n $(expr $(tput lines) - 1)
    fi
}

How can it be simplified to avoid repetition?

3

Noting that grep with an empty pattern '' matches every line, you could just always use it without testing:

h(){ 
    history | grep "$1" | tail -n $(($(tput lines)-1))
}
| improve this answer | |
  • Of course. I didn't think of quoting the argument, which is sort of required anyway. And a more compact calculation of screen lines too. Very nice! – forthrin Sep 20 '16 at 10:39
2

You can pipe in and out of conditional statements:

h() {
    history |
    if [ $# -eq 1 ]; then
        grep $1
    else
        cat
    fi |
    tail -n $(expr $(tput lines) - 1)
}

The cat is a no-op filter for symmetry.

| improve this answer | |
  • I didn't know if fit within a pipe, but it makes absolute sense, as does the cat. Is it possible to lose if and friends in favor of some more compact syntax like [ .. ] &&? – forthrin Sep 20 '16 at 9:36
  • 1
    @forthrin Suggestion for added feature: use grep "$@" instead of grep $1, this allows you to pass options to grep, e.g. type h -i foo and grep for foo case-insensitive. – Jens Sep 20 '16 at 10:57
  • Good thought, but putting the grep options inside the quotes fails, doesn't it? – forthrin Sep 20 '16 at 11:08
  • @forthrin No, "$@" is special in the shell. When double quoted it expands to each positional parameter, with spaces in each parameter preserved. Try set a "foo bar"; printf '<%s>\n' "$@" to see this in action! This would not work with "$*". – Jens Sep 20 '16 at 11:49
  • With "$@", h without any arguments produces usage: grep.... So currently I'm using "$1" unless you have a fix. – forthrin Oct 20 '16 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.