I am trying to run a Python program through a Bash script. When I execute the python file by shell it works with no problem, but when I try to execute the script, the python
keyword is not recognized.
I have a fresh Ubuntu 23.10 installation and I added, on top of the ~/.bashrc
file, the following line:
alias python=python3
How to solve this problem?
Toy example
For sake of simplicity I made a toy example that displays the same behavior.
I have an hello-world.py
file, whose content is simply
print("Hello World!")
If I run it with the shell ($ python hello-world.py
), it works smoothly:
Hello World!
Now I created a script start.sh
whose content is:
#!/bin/bash
python hello-world.py
But if I execute it $ ./start.sh
I get the following error:
./start.sh: line 3: python: command not found
2
Answers
So, the issue is that your shebang isn’t running bash as a login shell (which is pretty normal). You are aliasing
python
topython3
in your.bashrc
, but that will only get run in a login shell. So try adding:to your shebang.
Although, to be clear, I would consider this a hack. I would suggest that ideally you just use
python3
in the shell script.Or, create a symlink. If you are on ubuntu, you can use
python-is-python3
:https://packages.ubuntu.com/focal/python-is-python3
.bashrc is not sourced when running noninteractive shell.
Aliases are disabled in noninteractive shell (by default).
A script is noninteractive, so these settings are ignored.
Refer to bash documentation on startup files.
Create a symlink in a directory added to PATH with the name python that links to python3 executable. For example
/usr/local/bin
or~/.local/bin
.Use your linux distribution specific settings, like
apt-get install python-is-python3
.Either way, use
python3
in your scripts anyway.