Search code examples
pythonterminalshvirtual-environmentbeeware

Why does this shell script fail, if it works when I enter each line into a terminal?


I've made a short shell script which goes like this:

#!/bin/sh

PROJECT_NAME="my_project"

mkdir $PROJECT_NAME
cd $PROJECT_NAME
python3 -m venv beeware-venv
source beeware-venv/bin/activate
python3 -m pip install briefcase
briefcase new

When I run this script with sh create_new_beeware_project, the first line to fail is source beeware-venv/bin/activate; the error I get is 'source: not found'. However, if I enter each line into the terminal one by one, everything works.

This isn't a big problem in and of itself; ultimately, I can just enter the commands manually. But it makes me think that there's something important about shell script that I haven't understood, and if possible I would like to have that explained to me.


Solution

  • There are two shells involved: your interactive shell, which is likely bash, and /bin/sh, your system's default POSIX shell. source is a non-standard alias for . which your /bin/sh does not recognize. Use . instead.

    #!/bin/sh
    
    PROJECT_NAME="my_project"
    
    mkdir "$PROJECT_NAME" || exit 1
    cd "$PROJECT_NAME"
    python3 -m venv beeware-venv
    . beeware-venv/bin/activate
    python3 -m pip install briefcase
    briefcase new