从不同位置运行 bash 脚本但引用脚本所在位置
我不久前写了一个脚本,可以为不喜欢命令行的人在 Linux 中执行一些简单的安装过程,但似乎他们是从某个位置(例如 root)运行该脚本。所以我心里有一个解决方案,但试图找出如何引用文件所在的位置。
例子。 我在 /root/Server/Scripts/ 文件夹中有一个名为 Install.sh 的脚本,它通过使用以下内容引用自身:
SCRIPTSDIR=`pwd`
我遇到了问题
但是,当人们通过执行 sh Server/Scripts/Install.sh 从 root 运行此脚本时, 我可以使 SCRIPTS= 引用文件所在位置而不是运行文件的位置吗?
谢谢,请问您是否需要更多信息!
编辑:所有答案都很好,我的意思是放置我需要的绝对路径。
I wrote a script a while back that would do some simple install procedures in linux for people that don't like the command line, but it seems that they are running the script from a location (such as root). So I have a solution in mind but trying to find out how to reference where the file is located.
Example.
I have a script called Install.sh in a folder /root/Server/Scripts/ which references itself by using the following:
SCRIPTSDIR=`pwd`
But I have come into problems with people running this script from root by doing sh Server/Scripts/Install.sh
How could I make SCRIPTS= something that references where the file is located, not where it is being run from?
Thanks, ask if you need more info!
Edit: All answers were good, I meant to put I needed absolute path.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过以下方式获取 dir
如果使用相对路径调用脚本,则 dirname 还将返回相对路径。如果您出于某种原因想解决它,您可以这样做
You can get dir with
If your script is called with relative path, dirname will also return relative path. If you want to resolve it for some reason, you can do
您可以使用:
如果您需要绝对路径,请尝试:
You can use:
If you need absolute path, then try:
你可以添加类似的内容:
You could add something like: