1

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`'
Yusuf
  • 2,295
  • 7
  • 15
  • 34
  • You could use the 'command' command – Saxtheowl Apr 14 '23 at 21:57
  • 1
    Does [this other Q&A help?](https://stackoverflow.com/q/592620/289011) – Savir Apr 14 '23 at 21:59
  • It's not your script's job to worry about this. Use `python`, and document that the person *running* your script needs to have an appropriate `python` command in their environment. (Most likely, they will use a virtual environment created with whatever version of Python is deemed appropriate.) – chepner Apr 14 '23 at 22:42
  • At most, I would require the user to set `PYTHON` in the environment to an appropriate name (for path lookup) or path (relative or absolute) to the desired interpreter. – chepner Apr 14 '23 at 22:47

1 Answers1

0

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"
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32