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 Answers
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.
Comments
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
E L
May want to redirect &>/dev/null as Eugene does above if you want to silence the error.
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
Devis L.
This approach throws an error if it is not installed
which python3and check the exit code?whichis slow and unreliablepython3will never be a built-in)? I can see thatcommandis a little faster, but I'd hardly call 3 ms forwhich python3to be 'slow', either.