You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何让Bash脚本获取调用自身的软链接名称?

Great question! You’ve already noticed that C programs retain the symlink name via argv[0], but your initial Bash approach using readlink -f resolves to the original script file instead. The fix is simpler than you might think—Bash actually gives you the symlink name directly through the $0 variable, no need for readlink -f.

Here's the corrected script

Update your checkbash.bash to use $0 (or basename "$0" if you just want the filename without the path):

#!/bin/bash
# file: checkbash.bash
# Print the full invocation path (including symlink)
echo "$0"
# Or just the symlink filename
echo "$(basename "$0")"

Let's test it

Run the same symlink setup and invocation:

$ ln -s checkbash.bash ppb
$ ./ppb
./ppb
ppb

Why your original approach didn't work

readlink -f $0 specifically resolves symlinks to their target file—it’s designed to follow the link chain to the actual underlying file. That’s why it returned checkbash.bash instead of ppb.

In contrast, $0 in Bash holds the exact string used to invoke the script, whether that’s a relative path, absolute path, or symlink. Adding quotes around "$0" also ensures it handles paths with spaces correctly, which is a good practice for robust scripts.

Bonus: Handling absolute path invocations

If you call the symlink using an absolute path like /home/youruser/ppb, basename "$0" will still correctly extract ppb as the output.

内容的提问来源于stack exchange,提问作者Scorpious

火山引擎 最新活动