Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I thought it would be nice to have an alias (in ~/.zshrc) to have 'python' aliased to 'ipython' ONLY when 'python' is run without args (otherwise, programs won't launch). First of all, how to express "without args" in an alias? Secondly, what do you think about it?

share|improve this question
    
Be more specific as to what you want to accomplish. –  schaiba Feb 16 '13 at 14:44

2 Answers 2

up vote 5 down vote accepted

Shell aliases, by definition, don't give you any way to use them conditionally. They apply to anything you run from an interactive prompt.

The way you can do this is with a function instead. (See In Bash, when to alias, when to script, and when to write a function? for more on why this is different.)

function python () {
    test -z "$1" && ipython || command python "$@"
}

Something along those lines in your shell's rc file will cause your shell to run this function instead of the binary directly. If the first argument is blank, it will fire off ipython for you, otherwise it will pass on all arguments to whatever python binary is in your path (note the use of command to force the binary rather than the function to execute and cause a recursion on itself).

share|improve this answer
    
This will also execute on python '', and you will also execute python if ipython returns an exit code >0. function also makes this non-POSIX when it doesn't really need to be. –  Chris Down Feb 16 '13 at 15:38
    
@ChrisDown All of those "side effects" are intentional here. If a blank argument is specified, ipython should be able to handle it. If ipython fails for some reason (such as not existing on the system), trying regular python seemed like a good option. Using function is just a ZSH convention, but your right it would work without that. –  Caleb Feb 16 '13 at 15:46
    
That isn't an alias, it's a shell function. At least in bash, aliases just replace the command name by a string of fixed words; no arguments as such handled, no logic. –  vonbrand Feb 16 '13 at 16:54
1  
@vonbrand I didn't say it was an alias. In fact I said that an alias would not work for this problem and that a shell function was needed instead. –  Caleb Feb 16 '13 at 18:34

Not sure if you can do it in an zsh alias, but why not stick this small shell script in your ~/bin as python:

#!/bin/bash
if test -z "$1"; then
    exec /usr/bin/ipython
else
    exec /usr/bin/python "$@"
fi
share|improve this answer
2  
This will also execute on python ''. –  Chris Down Feb 16 '13 at 15:37
    
As if you'd actually do that :) –  Dennis Kaarsemaker Feb 16 '13 at 15:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.