我如何找到一个Bash脚本位于该脚本内部的目录的路径?

我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:

$ ./application

当前回答

#!/bin/sh
PRG="$0"

# need this for relative symlinks
while [ -h "$PRG" ] ; do
   PRG=`readlink "$PRG"`
done

scriptdir=`dirname "$PRG"`

其他回答

我认为最简单的答案是原始变量的参数扩展:

#!/usr/bin/env bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo "opt1; original answer: $DIR"
echo ''

echo "opt2; simple answer  : ${BASH_SOURCE[0]%/*}"

它应该产生产量如:

$ /var/tmp/test.sh
opt1; original answer: /var/tmp

opt2; simple answer  : /var/tmp

变量/参数扩展 ${BASH_SOURCE[0]%/*}”似乎更容易保持。

我想确保剧本在其目录中运行。

cd $(dirname $(which $0) )

接下来,如果你真的想知道你在哪里运行,然后运行下面的命令。

DIR=$(/usr/bin/pwd)

使用“0”字母:

#!/usr/bin/env 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

您可以使用 $BASH_SOURCE:

#!/usr/bin/env bash

scriptdir="$( dirname -- "$BASH_SOURCE"; )";

请注意,您需要使用 #!/bin/bash 而不是 #!/bin/sh 因为它是一个 Bash 扩展。

简短答案:

"`dirname -- "$0";`"

或(最好是):

"$( dirname -- "$0"; )"