Bash覆盖$ 0 - 脚本的名称

时间:2015-09-02 09:47:45

标签: bash symlink

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

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

2 个答案:

答案 0 :(得分:2)

如果它是一个脚本,如果它可以被采购:

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

适用于我的案例。

答案 1 :(得分:0)

虽然这个想法永远不会在我的脑海中浮现,但我还是尝试了一下。 我的结论是:你不能(至少不能)。

以下是如何以及为什么假装你使用$ 1作为想要的符号链接。

#!/bin/bash

# not surprisingly, you cannot do this:
# 0 = $1
# '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:
# $0 = $1
# but say your script is called as ./foobar.sh, this will actually result in:
# ./foobar.sh = whatever_$1_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 = $1
# ...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 = $1 # to be replaced with called_as = $0 once you're done prototyping
# if called_as such name do this
# if called_as such other name do that