如何在Bash脚本中获取该脚本所在目录的路径?
我想使用Bash脚本作为另一个应用程序的启动器。我想将工作目录更改为Bash脚本所在的目录,这样我就可以对该目录中的文件进行操作,如下所示:
$ ./application发布于 2008-09-12 20:49:29
使用dirname "$0"
#!/bin/bash
echo "The script you are running has basename `basename "$0"`, dirname `dirname "$0"`"
echo "The present working directory is `pwd`"如果不是从脚本所在的目录运行脚本,则仅使用pwd将不起作用。
[matt@server1 ~]$ pwd
/home/matt
[matt@server1 ~]$ ./test2.sh
The script you are running has basename test2.sh, dirname .
The present working directory is /home/matt
[matt@server1 ~]$ cd /tmp
[matt@server1 tmp]$ ~/test2.sh
The script you are running has basename test2.sh, dirname /home/matt
The present working directory is /tmp发布于 2008-09-12 20:50:56
您可以使用$BASH_SOURCE
#!/bin/bash
scriptdir=`dirname "$BASH_SOURCE"`请注意,您需要使用#!/bin/bash而不是#!/bin/sh,因为它是一个Bash扩展。
发布于 2008-12-03 12:57:40
简短的回答:
`dirname $0`或(preferably):
$(dirname "$0")https://stackoverflow.com/questions/59895
复制相似问题