我正在写一个Bash脚本。我需要当前工作目录始终是脚本所在的目录。

默认行为是脚本中的当前工作目录是我从中运行它的shell的目录,但我不想要这种行为。


当前回答

获取脚本的真实路径

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)

(这是对我这里相同问题的回答:获取脚本执行的目录的名称)

其他回答

这个脚本似乎对我有用:

#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd

无论从哪里运行,pwd命令行都将脚本的位置返回为当前工作目录。

#!/bin/bash
cd "$(dirname "$0")"

如果你只是需要打印当前的工作目录,那么你可以这样做。

$ vim test

#!/bin/bash
pwd
:wq to save the test file.

给予执行权限:

chmod u+x test

然后通过./test执行脚本,然后可以看到当前的工作目录。

获取脚本的真实路径

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)

(这是对我这里相同问题的回答:获取脚本执行的目录的名称)

我吃了这个,它起作用了。

#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)