8

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?

phunehehe
  • 20,240

3 Answers3

7

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.

Mikel
  • 57,299
  • 15
  • 134
  • 153
  • Don't you mean ~/.bashenv in step 4? – cjm Mar 02 '11 at 02:47
  • So I'll have to change the script anyway, from #!/bin/sh to #!/bin/bash? Can I just do bash my-script? – phunehehe Mar 02 '11 at 02:48
  • phunehehe: Yes, I think bash my-script will work if you still do steps 1-4. – Mikel Mar 02 '11 at 02:50
  • I don't recommend using aliases in scripts. It won't work if someone else runs your script, or if you run the script under sudo or other privilege elevation method. And it doesn't allow you to change the virtualenv per execution, which would be the main point of not having ~/virtualenv/bin in your PATH permanently. Adding the directory in front of the PATH when needed is the best method. – Gilles 'SO- stop being evil' Mar 02 '11 at 08:02
4

Supposing that your alias file is "~/.bash_aliases", put this in your script:

#!/bin/bash
shopt -s expand_aliases
source ~/.bash_aliases
python run-project.py

(via)

tshepang
  • 65,642
0

Alternatively, you can always source your script to forcely use the aliases. For example, let's assume you have an alias of rm in your ~/.bashrc:

alias rm='moveToTrash'

while moveToTrash is a program in your /usr/bin. Now you have a script named test.bash like this:

#!/bin/bash

which rm

When test.bash is execute directly, you can see the output /bin/rm, while source test.bash will get the output

alias rm='moveToTrash'
    /usr/bin/moveToTrash
Mark Z.
  • 101