简体   繁体   中英

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

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.

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

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, "$@"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM