我正在写一个Bash脚本。我需要当前工作目录始终是脚本所在的目录。
默认行为是脚本中的当前工作目录是我从中运行它的shell的目录,但我不想要这种行为。
我正在写一个Bash脚本。我需要当前工作目录始终是脚本所在的目录。
默认行为是脚本中的当前工作目录是我从中运行它的shell的目录,但我不想要这种行为。
当前回答
cd "$(dirname "${BASH_SOURCE[0]}")"
很容易。它的工作原理。
其他回答
cd "`dirname $(readlink -f ${0})`"
echo $PWD
PWD是一个环境变量。
这个脚本似乎对我有用:
#!/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执行脚本,然后可以看到当前的工作目录。