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\$
  • 2
    \$\begingroup\$ Please explain what this code accomplishes, and what these conditions are. See How to Ask. \$\endgroup\$ – 200_success Feb 24 '19 at 22:00
  • \$\begingroup\$ Install a Python package, based on 2 variables: active_gpu or version. Code is itself explanatory \$\endgroup\$ – gogasca Feb 25 '19 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 Feb 26 '19 at 18:26
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
| improve this answer | |
\$\endgroup\$

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