Linux – Activate virtualenv using alias

bashrclinuxshell-scriptvirtualenv

I can activate my python virtual environment from it's folder by entering . bin/activate. I'd like to instead type a single word alias, such as shazam, from the home folder (or anywhere else) that activates the environment, changes to my master project folder, and lists my projects.

I tried creating an alias in .bashrc that pointed to an .sh file containing:

cd ~/path-to-virtual-environment
. bin/activate
cd ~/path-to-master-project-folder
ls -a

I was getting a permission denied error, so I ran chmod u+x <script file>. The script now runs, but the VE does not activate and while the project folders are listed, the shell is not in the master project folder. I would appreciate some guidance. Thanks.

NOTE: I received an ANSWER on another forum. Shell scripts do not change the environment from which they're called; instead, use a shell function inside .bashrc.

shazam () {
  source ~/path-to-virtual-environment/bin/activate
  cd ~/path-to-master-project-folder
  ls -a
}

Best Answer

Alias can have list of commands:

alias shazm='source ~/path-to-virtual-environment/bin/activate; cd ~/path-to-master-project-folder; ls -a'
Related Question