2
#!/bin/bash
python3 -c "import numpy"
if [ $? ]; then
    echo Numpy needs to be installed
    sudo apt-get python3-numpy
fi
echo Everything is properly installed

This is what I'm trying to run.

Supposedly, it checks if numpy is already installed and if not, install it. However, it installs everytime, even though I already have it.

When I change import numpy to import asdfas it still installs numpy, so the if is not doing anything at all!

I'm sorry if this is already answered, but my google search didn't find this specific error

  • This wasn't your question, but I'd lilke to point out: if installing fails (e.g. the user enters incorrect password multiple times, or any other error), your script still reports that everything is properly installed. – egmont Jun 4 '19 at 18:44
  • @egmont Feel free to edit the answer and suggest a better way! – dessert Jun 5 '19 at 17:55
2

The if expression can easily be a command, so that the then statement is executed if the command ran successfully and the else statement if not. Using ! it’s possible to invert this behaviour, so just use if ! python3 …:

#!/bin/bash
if ! python3 -c "import numpy"; then
  echo Numpy needs to be installed
  sudo apt-get python3-numpy
fi
echo Everything is properly installed
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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