29

I am writing a shell script, and before the script runs I want to verify that the user has Python 3 installed. Does anyone know or have any ideas of how I could check that, and the output be a boolean value?

3
  • 3
    which python3 and check the exit code? Commented Jul 20, 2016 at 15:59
  • 1
    @MartijnPieters which is slow and unreliable Commented Jul 21, 2020 at 15:46
  • @Sapphire_Brick: how is it unreliable for executable files (python3 will never be a built-in)? I can see that command is a little faster, but I'd hardly call 3 ms for which python3 to be 'slow', either. Commented Jul 25, 2020 at 16:02

3 Answers 3

43

Interactive shell

Simply run python3 --version. You should get some output like Python 3.8.1 if Python 3 is installed.

Shell script

You can use the command or type builtins:

command -v python3 >/dev/null 2>&1 && echo Python 3 is installed  # POSIX-compliant
type -P python3 >/dev/null 2>&1 && echo Python 3 is installed     # Bash only

Using which is not recommended as it requires launching an external process and might give you incorrect output in some cases.

Sign up to request clarification or add additional context in comments.

Comments

5

execute the following command. which python3 and check the exit status of the command $?. it will be 0 if user has python 3 installed, 1 otherwise.

1 Comment

May want to redirect &>/dev/null as Eugene does above if you want to silence the error.
4

You can check it with regular expression match, on the "python3 -V" output.

For example:

[[ "$(python3 -V)" =~ "Python 3" ]] && echo "Python 3 is installed"

1 Comment

This approach throws an error if it is not installed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.