1
\$\begingroup\$

I have the following code, is there a way to optimize it/reduce the code?

  #!/bin/bash

  if [[ "${active_gpu}" == 'true' ]]; then
    if [[ "${version}" == 'dev-gpu' ]]; then
        pip install "${version}"
    else
        pip install package-gpu=="${version}"
    fi
  else
    if [[ "${version}" == 'nightly' ]]; then
        pip install "${version}"
    else
        pip install package=="${version}"
    fi
  fi
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Please explain what this code accomplishes, and what these conditions are. See How to Ask. \$\endgroup\$ Commented Feb 24, 2019 at 22:00
  • \$\begingroup\$ Install a Python package, based on 2 variables: active_gpu or version. Code is itself explanatory \$\endgroup\$
    – gogasca
    Commented Feb 25, 2019 at 4:20
  • \$\begingroup\$ @spicyramen You're setting yourself up for some close votes. You should take the 2 minutes to explain in your post what your code is supposed to do even if it can be clarified by looking at the code :) \$\endgroup\$
    – IEatBagels
    Commented Feb 26, 2019 at 18:26

1 Answer 1

2
\$\begingroup\$

For this kind of problem you want to build a command line with variables, and run it only once.

You only have a few cases but the benefits of this approach become apparent as you add more cases: you don't need an exponential number of branches to keep up.

This code does not exactly follow the logic of your code but it's probably close enough. I'm using an associative array to build the param variable, and bash regular expressions to test for multiple no-param cases.

#!/bin/bash
declare -A gpu_param=( [true]=-gpu )
[[ $version =~ nightly|dev-gpu ]] || param=package${gpu_param[$active_gpu]}==
pip install $param$version
\$\endgroup\$

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