基本上我需要运行与shell脚本文件位置相关的路径脚本,我如何将当前目录更改为脚本文件所在的相同目录?


当前回答

让我们把它变成一个POSIX在线程序:

a="/$0"; a="${a%/*}"; a="${a:-.}"; a="${a##/}/"; BINDIR=$(cd "$a"; pwd)

在包括BSD在内的许多兼容bourne的shell上进行了测试。

据我所知,我是作者,我把它放到了公共领域。更多信息见: https://www.bublina.eu.org/posts/2017-05-11-posix_shell_dirname_replacement/

其他回答

灵感来自blueyed的回答

read < <(readlink -f $0 | xargs dirname)
cd $REPLY

如果您正在使用bash....

#!/bin/bash

pushd $(dirname "${0}") > /dev/null
basedir=$(pwd -L)
# Use "pwd -P" for the path without links. man bash for more info.
popd > /dev/null

echo "${basedir}"

让我们把它变成一个POSIX在线程序:

a="/$0"; a="${a%/*}"; a="${a:-.}"; a="${a##/}/"; BINDIR=$(cd "$a"; pwd)

在包括BSD在内的许多兼容bourne的shell上进行了测试。

据我所知,我是作者,我把它放到了公共领域。更多信息见: https://www.bublina.eu.org/posts/2017-05-11-posix_shell_dirname_replacement/

基本版:

dir=$(dirname $0)

如果脚本可以通过$PATH调用,那么:

dir=$(dirname $(which $0))

如果脚本可能像这样调用:bash script.sh,那么:

dir=$(dirname $(which $0 2>/dev/null || realpath ./$0))

如果你感到极度不安全,那么:

dir="$(dirname -- "$(which -- "$0" 2>/dev/null || realpath -- "./$0")")"

最初的帖子包含了解决方案(忽略回复,他们没有添加任何有用的东西)。有趣的工作是由前面提到的unix命令readlink和选项-f完成的。当以绝对路径和相对路径调用脚本时,此方法有效。

对于bash, sh, ksh:

#!/bin/bash 
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH

对于tcsh, csh:

#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH

参见:https://stackoverflow.com/a/246128/59087