Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can determine to run a script using `python` or `python3` depending on the installed version of python?

I have a script file myfile.sh and contains the following

#! /bin/bash

set -e

MYVAR=`cat $1 | python -c 'import os`'

The question is, how I can make a condition to use python3 if python3 is installed or in other word(python is > 3) and use python if the installed version of is < 3 something like:

#! /bin/bash
set -e
#  CONSIDER THIS SUDO CODE 
if 'python3 --version' !== 'command not found or something null'; then     # SUDO CODE
  PYTHON=python3
else
  PYTHON=python
fi

MYVAR=`cat $1 | PYTHON -c 'import os`'
like image 544
Yusuf Avatar asked Mar 08 '26 18:03

Yusuf


1 Answers

The command command would allow you to check if python3 is available and use it.

for example in the below script python3 will be used and if not possible it will use python:

#!/bin/bash

set -e

if command -v python3 &>/dev/null; then
    PYTHON=python3
else
    PYTHON=python
fi

MYVAR=$(cat "$1" | $PYTHON -c 'import sys, os; print("Hello from", sys.version)')

echo "$MYVAR"
like image 107
Saxtheowl Avatar answered Mar 11 '26 06:03

Saxtheowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!