0

I have a simple bash script that goes like this,

#!/bin/bash

arg=$0
size=${#arg}

if [ "$size" -gt 5 ]; then
   
   # ok
   python -c "module('$arg')"  # << python call
   exit 0;
   
else
   echo "Error : Argument too short.";
   exit 1;
fi

which calls python module with the argument. This scheme works on a computer that has conda installed, where python just refers to the python interpreter of the currently active conda environment.

When I run this script on a computer which does not have conda, it gives error that it cannot find python. Understandable since the system's python is available as python3 (for example on ubuntu). In this case, the script runs if the python call is changed to python3 -c "module('$arg')"

How to make sure that the script calls python, first checking for conda and then if not, using the system's python. Essentially trying to make the script more fail-safe.

Any hints. Thanks.

ankit7540
  • 315
  • 5
  • 20

1 Answers1

1

Both the command bash builtin and the commonly-available which(1) will allow you to test if something is available on PATH.

e.g.

command -v python3 >/dev/null && PYTHON_BIN=python3 || PYTHON_BIN=python
$PYTHON_BIN -c 'print("Hello")'
tonymke
  • 752
  • 1
  • 5
  • 16
  • 1
    More info: https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script – tonymke Feb 05 '22 at 05:02