Bash 覆盖 $0 - 脚本的名称

Bash override $0 - the name of the script

有一个类似 busybox 的 shell 脚本,它根据调用它的符号链接来决定要做什么。

我想直接调用它并传递符号链接的名称,而不实际创建符号链接。

虽然我从来没有想过这个想法,但我试了一下很有趣。 我的结论:你不能(至少,不能)。

以下是方法和原因,假设您使用 $1 作为可能的符号链接。

#!/bin/bash

# not surprisingly, you cannot do this:
# 0 = 
# '0' is not a valid variable name, so bash try to use it as a command, hence:
# 0: command not found

# you CAN do this, as meaningless as it seem:
# [=10=] = 
# but say your script is called as ./foobar.sh, this will actually result in:
# ./foobar.sh = whatever__is
# ...which is a nice fork bomb, since you'll call your script again,
# which will call your script again,
# which will call your script again,
# which will call ...etc etc etc
# Try it! :-)

# I've just learned about $BASH_SOURCE from here:
# http://www.tldp.org/LDP/abs/html/debugging.html#BASHSOURCEREF
echo BASH_SOURCE $BASH_SOURCE
# you CAN do this:
BASH_SOURCE = 
# ...but to no use, since the following will show that BASH_SOURCE
# rightfuly behave as read-only:
echo BASH_SOURCE $BASH_SOURCE #unmodified

因此,如果您的想法是在不创建符号链接的情况下对 "a la busybox" 行为进行原型设计,我建议:

#!/bin/bash
called_as =  # to be replaced with called_as = [=11=] once you're done prototyping
# if called_as such name do this
# if called_as such other name do that

如果是脚本并且可以获取来源:

bash -c '. script.sh' overridden-name param1 param2

适合我的情况。