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

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


当前回答

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

其他回答

cd "`dirname $(readlink -f ${0})`"

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

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

PWD是一个环境变量。

这个脚本似乎对我有用:

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

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

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