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\$

closed as off-topic by 200_success, Toby Speight, Gerrit0, IEatBagels, ferada Feb 26 at 23:22

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, Gerrit0, IEatBagels, ferada
If this question can be reworded to fit the rules in the help center, please edit the question.

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

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