Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of alias that invoked bash script

$0 expands to the name of the shell script.

$ cat ./sample-script
#!/bin/bash
echo $0
$ chmod 700 ./sample-script
$ ./sample-script
./sample-script

If the shell script is invoked via a symbolic link, $0 expands to its name:

$ ln -s ./sample-script symlinked-script
$ ./symlinked-script
./symlinked-script

How could I get the name of an alias? Here `$0' expands again to the filename:

$ alias aliased-script=./sample-script
$ aliased-script
./sample-script
like image 223
xebeche Avatar asked Apr 22 '12 19:04

xebeche


3 Answers

Aliases are pretty dumb, according to the man page

...Aliases are expanded when a command is read, not when it is executed...

so since bash is basically just replacing a string with another string and then executing it, there's no way for the command to know what was expanded in the alias.

like image 150
Shep Avatar answered Oct 17 '22 12:10

Shep


I imagine you already know this, but for the record the answer is: you need cooperation by the code implementing the alias.

alternate_name () {
  MY_ALIAS_WAS=alternate_name real_name "$@"
}

or, if you really want to use the superseded alias syntax:

alias alternate_name="MY_ALIAS_WAS=alternate_name real_name"

...and then...

$ cat ~/bin/real_name
#!/bin/sh
echo $0, I was $MY_ALIAS_WAS, "$@"
like image 42
DigitalRoss Avatar answered Oct 17 '22 14:10

DigitalRoss


bash does not make this available. This is why symlinks are used to invoke multiplex commands, and not aliases.

like image 2
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 14:10

Ignacio Vazquez-Abrams