1

I have python installed on my system as python3. In my .zshrc file I defined following alias:

alias python=python3

With this, I am able to run python3 using python on the command-line:

$ python
Python 3.11.6 (main, Nov  2 2023, 04:39:43) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

But if I write a shell script test.sh like so:

#!/bin/bash
python

and then try to run this script as follows:

$ ./test.sh

I get:

./test.sh: line 2: python: command not found

What is going on here and how can I fix it? To be clear, this is on Mac but I think the result should be same on Linux. Thanks.

1
  • 1
    If you want to run bash in your script and have it use that alias then put the alias in your .bashrc, not your .zshrc, as bash and zsh are 2 completely different shells.
    – Ed Morton
    Commented Jan 11 at 18:24

2 Answers 2

0

Aliases and functions do not propagate to shell scripts. This is by design. They allow you to define nonstandard behavior for standard command names. Having those available in a script is likely to disrupt the script. This is especially true of aliases that are commonly used to add default options to commands.

If you have a script that expects a command that you have under a different name, create a symbolic link to that command in a directory that's in the $PATH. If the script needs a nonstandard version of a command, use a dedicated directory for running the script. For example, if you have a script that calls python explicitly, or a script with a #!/usr/bin/env python shebang line, and you want it to invoke some different version of Python:

  1. Create a directory e.g. mkdir ~/myscript-bin
  2. Link the version you want in that directory, e.g. ln -s /usr/bin/python4.2 ~/myscript-bin/python
  3. When running the script, put this directory first in the command search path: PATH=~/myscript-bin:$PATH myscript

For Python, there's quite a bit of tooling to help with having several versions around, and especially helps with managing libraries. If you have a script that requires a non-default version of Python or a non-default set of Python libraries, create a virtual environment for it.

python4.2 -m venv ~/myscript-env
# If the script needs extra packages:
(. ~/myscript-env/activate && pip install package1 package2)
(. ~/myscript-env/activate && myscript)
0

As Ed explained, zsh and bash are 2 different environments. Since Apple changed its default shell to zsh and I still write my shell scripts in bash, I ended up placing my aliases in a .alias file then have both .zshrc and .bashrc source that. I did the same for my functions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .