Tuesday, March 15, 2022

[SOLVED] Is it possible to use the source command multiple times on different files?

Issue

I currently try to write a bash script which should help me to automate the virtual enviroments in python alittle bit. The problem is that it seems that I am not able to source twice. (Sourcing in a bash script another bash script).

These are the files which I use:

#!/bin/bash
# Call this file with . filename or source filename to run it in the current bash
if [ "$#" -eq 1 ]
then
    if [ "$1" == "install" ]
    then
        pip install kivy[base]
        # Install Kivy and some examples
        #python -m pip install kivy[base] kivy_examples
    elif [ "$2" == "start" ]
    then 
        source ../virtualEnviroment.sh Kivy
    fi
fi

virtualEnviroment.sh:

#!/bin/bash
# Call this file with . filename or source filename to run it in the current bash
ENVIROMENTNAME=$1
DIR=$1
(return 0 2>/dev/null) && sourced=1 || sourced=0

if [ "$#" -ne 1 ]
then
    echo Missing enviromentname
else
    if [ "$sourced" -eq 1 ]
    then
        if [ -d "$DIR" ]
        then
            echo Using existing enviroment $ENVIROMENTNAME
            source "$ENVIROMENTNAME"/bin/activate
        else
            echo Creating new enviroment $ENVIROMENTNAME
            python3 -m virtualenv "$ENVIROMENTNAME"
            source "$ENVIROMENTNAME"/bin/activate
        fi
    else

        echo Please use . $0 or source $0
    fi
fi

Did I do something wrong, or is it normal that I only can source one time?

(Does it try to use the bash environment of the first bash script, but since it is already sourced, it can not use the sourced bash environment and use the unsourced bash environment of the first bash script?)


Solution

It seems I just forgot to add another source to the bash script to source the second bash file too.



Answered By - DJPX
Answer Checked By - Marilyn (WPSolving Volunteer)