How to get the name of the alias that called the bash script

$0 expands to shell script name.

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

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

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

How can I get the alias name? Here, `$ 0 'returns again to the file name:

$ alias aliased-script=./sample-script
$ aliased-script
./sample-script
+5
source share
3 answers

I think you already know this, but for the record, the answer is: you need cooperation using code that implements an alias.

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

or, if you really want to use the replaced 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, "$@"
+2
source

Aliases are pretty dumb, according to the man page

... Aliases expand when reading a command, and not when it is executed ...

bash , , .

+6

bash does not make this available. This is why symbolic links are used to invoke multiplexing commands rather than aliases.

+2
source

All Articles