Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

Today, I learned the very handy trick:

man [some command] -t | open -f -a Preview

I'd like to create an alias in my .bash_profile file as a shortcut. In order for this to work, I need to pass an argument into the aliased command. A little poking around and I came up with this:

alias manp="man $1 -t | open -f -a Preview"

This almost works, but if I type in, say "manp ls", it seems to be expecting the ls manpage to be in whatever my current directory is.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

You can't pass arguments to aliases. Aliases are just text substitutions without further logic.

But you can use shell functions to achieve the same result:

function pman() {
    if [ -x /usr/bin/open ]; then
        man -t "$1" | open -f -a Preview
    else
        man "$1"
    fi
}

The if-then-else part is there just to make sure it also works on non-OSX systems.

To define a function, just include the definition from above into your ~/.bash_profile. Usage is identical to aliases or any other command: pman ls.

As @stuffe pointed out in a comment keeping aliases/functions in a separate file has its advantages (especially it allows you to re-read your aliases/functions into the current shell without executing any setup stuff from .bashrc or .bash_profile). To do this, create a separate file called .alias, .functions or similar and add

test -e ~/.alias && . ~/.alias

to .bashrc or .bash_profile.

share|improve this answer
1  
I like to keep all my functions in a separate file (functions.fn), and call that from within whatever .profile your shell of choice uses. To expand on Patrix excellent answer, $1 is the name of the first passed argument, $2 is the 2nd etc. For clarity and as a form of self commenting my functions the first thing I do in anything thats more than a couple of lines is rename them with moredescriptivename=$1 etc. –  stuffe Nov 6 '11 at 11:22
    
good point, I've extended the answer accordingly –  patrix Nov 6 '11 at 13:05
add comment

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.