1

TL:DR How do I add a grep to a bash function while allowing a variable number of optional inputs?

I find that in repeated grepping of large outputs, I end up clogging the terminal with data. Sometimes, I want to do a grep, and quickly go to the top of it while capturing all the data. To this end, I have become accustomed with using "clear;clear; grep [options] [string] [file] ; top". Being lazy, I want to turn this into a function called "cgrep", which performs the two clears and the grep. What I have tried is:

cgrep () {
   clear
   clear
   grep "$1" "$2" "$3"
}

This works, providing that I always use exactly one optional argument. While that isn't a problem most of the time, I became curious about how to feed it 0-N optional arguments without causing issues (such as reading the [string] as [file]).

I've read this post, and tried a similar implementation. However, this didn't quite suit my needs, and it would be better if I could have the optional parameters between cgrep and [string] to make it look more like a traditional grep.

8
  • Are you asking how the function can test for no arguments and exit with a message rather than invoke the clear and grep commands?
    – Sotto Voce
    Sep 22, 2022 at 18:11
  • @SottoVoce I'm hoping to learn how to invoke the grep command correctly with 0-N optional parameters. Currently, 0 parameters will try to use [string] as an optional parameter, and 2 parameters will try to use [string] as [file]. Is there a way for the function to understand what is or isn't an optional parameter, just like running grep by itself through the terminal would? Sep 22, 2022 at 18:15
  • 1
    Why would you call clear twice in a row? Sep 22, 2022 at 19:01
  • @StéphaneChazelas One clear will get rid of most of the buffer, but it leave the previous called output of top at the top of the window. Using clear twice will truly remove all entries from the buffer, so I know that if I scroll all the way up, I will be at the top of what I just queried. This just makes checking things a little bit faster, and it looks nicer. Sep 23, 2022 at 10:37
  • 1
    There seems to be something wrong with your clear or terminal emulator. What terminal emulator are you using? What's the output of echo "$TERM"; clear | LC_ALL=C sed -n l? Sep 23, 2022 at 11:00

1 Answer 1

2

In bash and sh "$@" will expand all positional parameters so:

cgrep () {
   clear
   clear
   grep "$@"
}

Note that $@ has to be double quoted to prevent word splitting, globbing, empty removal, etc from being performed on each parameter.

3.4.2 Special Parameters

2
  • Tried it and it worked perfectly! Will set it as the accepted answer asap! Thanks! Sep 22, 2022 at 18:19
  • 3
    It's not only word-splitting that quoting $@ prevents, it's also globbing (split+glob), and empty removal. Sep 22, 2022 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .