7

Is there a (somewhat) reliable way to get the 'origin' of a command, even if the command is an alias? For example, if I put this in my .bash_profile

alias lsa="ls -A"

and I wanted to know from the command-line where lsa is defined, is that possible? I know about the which command, but that doesn't seem to do it.

tripleee
  • 175,061
  • 34
  • 275
  • 318
user1516425
  • 1,531
  • 2
  • 15
  • 21
  • 6
    Did you try `type`? It doesn't show where it was defined, but does show the definition. – Carl Norum Jul 26 '12 at 01:08
  • @CarlNorum you should really just make that an answer. – kojiro Jul 26 '12 at 01:20
  • 2
    @kojiro, it doesn't really answer the question, which is about *where* the definition is. I thought it would be helpful information, though. – Carl Norum Jul 26 '12 at 01:37
  • @CarlNorum `which` also works for aliases – Sonique Jun 27 '14 at 18:25
  • 1
    The shell tracks the source file and line number where a function is defined, but not an alias. (You should be using functions rather than aliases anyhow, as they're considerably more flexible; for this particular alias, the equivalent function would be `lsa() { ls -A "$@"; }`). – Charles Duffy Sep 05 '16 at 20:08

3 Answers3

15

As Carl pointed out in his comment, type is the correct way to find out how a name is defined.

mini:~ michael$ alias foo='echo bar'
mini:~ michael$ biz() { echo bar; }
mini:~ michael$ type foo
foo is aliased to `echo bar'
mini:~ michael$ type biz
biz is a function
biz () 
{ 
    echo bar
}
mini:~ michael$ type [[
[[ is a shell keyword
mini:~ michael$ type printf
printf is a shell builtin
mini:~ michael$ type $(type -P printf)
/usr/bin/printf is /usr/bin/printf
kojiro
  • 74,557
  • 19
  • 143
  • 201
1

While type and which will tell you the source, they don't look up in several steps. I wrote a small program for this: origin. An example:

alext@smith:~/projects/origin$ ./origin ll
'll' is an alias for 'ls' in shell '/bin/bash': 'ls -alF'
'ls' is an alias for 'ls' in shell '/bin/bash': 'ls --color=auto'
'ls' found in PATH as '/bin/ls'
'/bin/ls' is an executable
alext@smith:~/projects/origin$
Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74
0

This function will provide with information on what type of command it is:

ft () {
    t="$(type -t "$1")";
    if [ "$t" = "file" ]; then
        if which -s "$1"; then
            file "$(which "$1")"
        else
            return 1
        fi
    else
        echo $t
    fi
    return 0
}

It will either spit out builtin, alias, etc., a line like /bin/ls: Mach-O 64-bit x86_64 executable if a file, or nothing if not present. It will return an error in that last case.

Coroos
  • 371
  • 2
  • 9