如何获取当前shell脚本的完整路径名?
有没有更简单的方法来做到这一点?
#!/bin/ksh
THIS_SCRIPT=$(/usr/bin/readlink -f $(echo $0 | /bin/sed "s,^[^/],$PWD/&,"))
echo $THIS_SCRIPT
我一直在使用 ksh,但更喜欢在 bash 中也能工作的解决方案(我认为确实如此)。
Is there a less brute-force way to do this?
#!/bin/ksh
THIS_SCRIPT=$(/usr/bin/readlink -f $(echo $0 | /bin/sed "s,^[^/],$PWD/&,"))
echo $THIS_SCRIPT
I'm stuck using ksh
but would prefer a solution that works in bash
too (which I think this does).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
bash 常见问题解答中的 条目 #28:
Entry #28 in the bash FAQ:
我一直这样做:
我以前从未使用过 readlink:它只是 Gnu 吗? (即它可以在 HP-UX、AIX 和 Solaris 上开箱即用吗?dirname 和 pwd 会......)
(编辑添加``,我在原始帖子中忘记了。d'oh!)
(编辑 2 添加两行,当我查看以前编写的脚本时,我显然总是这样做,但没有正确记住。第一次调用获取路径,第二次调用消除相对路径)
(编辑 3 个固定的拼写错误,导致单行答案无法工作,回到单行!)
I've always done:
I've never used readlink before: is it Gnu only? (i.e. will it work on HP-UX, AIX, and Solaris out of the box? dirname and pwd will....)
(edited to add `` which I forgot in original post. d'oh!)
(edit 2 to put on two lines which I've apparently always done when I look at previous scripts I'd written, but hadn't remembered properly. First call gets path, second call eliminates relative path)
(edit 3 fixed typo that prevented single line answer from working, back to single line!)
为什么我在问问题之前没有想到尝试一下?
效果很好。
Why didn't I think to try this before I asked the question?
Works great.
在 macOS 中,我使用(编辑:仅当您从脚本实际所在的位置运行脚本时才有效!)
my_script=$(pwd)/$(basename $0)
In macOS I use (edit: only works if you run the script from where the script actually is!)
my_script=$(pwd)/$(basename $0)