Shell – make scripts use aliases instead of commands

aliasshell-script

I have an alias for a command (I'm setting up a Python development environment)

alias python=~/virtualenv/bin/python

so that I can run ~/virtualenv/bin/python by just typing python. Now in my project there is a shell script that goes, for example:

#!/bin/sh
python run-project.py

Can I make the script use my aliased python instead of the python it finds in $PATH, without making changes to the script?

Best Answer

Yes.

If you put your aliases in ~/.aliases, then you can do

export BASH_ENV="~/.aliases"
somescript

This assumes your script starts with #!/bin/bash, because #!/bin/sh is a little less predictable.

Here's what I'd suggest:

  1. Create ~/.bashenv
  2. Move all the settings that you want to work in scripts from ~/.bashrc into ~/.bashenv
  3. Add this at the top of your ~/.bashrc:
    [ -f ~/.bashenv ] && source ~/.bashenv
  4. Put BASH_ENV=~/.bashenv in /etc/environment
  5. Make your scripts start with #!/bin/bash if they don't already

Or, if you're using zsh, just move your aliases into ~/.zshenv. zsh looks in that file automatically.


But maybe it's easier to just put ~/virtualenv/bin near the front of your PATH, then change your Python scripts to have #!/usr/bin/env python as the first line.

Related Question