Search code examples
bashshellpipegetopts

How to send ouput of branch if to pipe


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?


Solution

  • Try with

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