1

having this script:

if getopts "i" i; then
  grep -i | a lot of commands
else
  grep | a lot of commands
fi

The question is, I do not want to duplicate a lot of commands after the first entry to pipe, but the entry derive from a branch (whether getopts return 0 or 1). I want something like grep ${i:-defauloption} | ... and the defaultoption depends on the branch result - that is embed the branch before piped, rather then duplicating the a lot of commands with else branch, but just without the option (duplicated code). Is it possible to somehow avoid the duplication?

Herdsman
  • 799
  • 1
  • 7
  • 24

2 Answers2

3

Try with

if getopts "i" i; then
  grep -i 
else
  grep
fi | a lot of commands
Poshi
  • 5,332
  • 3
  • 15
  • 32
  • I didnt know, I can pass `fi` to pipe – Herdsman May 02 '20 at 19:41
  • I have another problem, When I do what you said, and execute with `-i` then it will execute `grep -i -i` with two `i` options set. Why? – Herdsman May 02 '20 at 19:53
  • You are not passing `fi` to pipe, you are passing the output of the `if..then..else..fi` conditional construct. – Poshi May 02 '20 at 20:17
  • About the double `-i`, I have no idea. You didn't showed the full code. – Poshi May 02 '20 at 20:20
  • here is full code https://stackoverflow.com/questions/61566331/why-is-optind-messing-my-positional-params – Herdsman May 02 '20 at 21:09
  • Because you are re-using the arguments that have already been parsed by getopts. Take a look at the answer by Walter A, as it also solves this issue. – Poshi May 02 '20 at 23:00
2

Store the variable part in a variable.

if getopts "i" i; then
  myoptions="-i"
fi
grep ${myoptions} | a lot of commands
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • I do not see positional params because of the `getopts`. The options messes with the input params. I somewhere found to do `((OPTIND -1))` - but I do not understand what that mean. but that doesnt work in my case, since I used the params in the branches, not after (the `((OPTIND-1))` should be used after `esac` according to some other questions. So how can I used options flag, and AFTER input params on invocation? – Herdsman May 02 '20 at 20:07
  • I hoped you knew what you was doing with the isolated `getopts` and `grep` command. The `getopts` call will look at an environment variable OPTIND and add one to it. To start over with the first argument, start a new shell or use `OPTIND=1`. When you want to parse the input variables, copy some `getopts` example with a `while` loop, and only parse the input in the loop. After the loop use the option variables that you have set. Or ask a new question when you are stuck with `getopts` in different situations. – Walter A May 02 '20 at 20:14
  • @Watler A : here is full code: https://stackoverflow.com/questions/61566331/why-is-optind-messing-my-positional-params – Herdsman May 02 '20 at 21:09