基本上我需要运行与shell脚本文件位置相关的路径脚本,我如何将当前目录更改为脚本文件所在的相同目录?
当前回答
cd $(dirname $(readlink -f $0))
其他回答
如果您正在使用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}"
正如marko所言:
BASEDIR=$(dirname $0)
echo $BASEDIR
除非你在脚本所在的目录中执行脚本,在这种情况下,你会得到一个值'。'
要解决这个问题,请使用:
current_dir=$(pwd)
script_dir=$(dirname $0)
if [ $script_dir = '.' ]
then
script_dir="$current_dir"
fi
现在可以在整个脚本中使用变量current_dir来引用脚本目录。然而,这可能仍然有符号链接的问题。
之前对一个答案的评论说过,但在所有其他答案中很容易被忽略。
使用bash时:
echo this file: "$BASH_SOURCE"
echo this dir: "$(dirname "$BASH_SOURCE")"
Bash参考手册,5.2 Bash变量
这个问题的最佳答案是: 从内部获取Bash脚本的源目录
它是:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
一行代码,它将提供脚本的完整目录名,无论从哪里调用脚本。
要了解它是如何工作的,你可以执行以下脚本:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
我发现的最有效的方法之一是
#!/bin/sh
relative_dir=`perl -e 'use Cwd "realpath";$pwd = realpath(shift); $pwd =~ s/\/[^\/]*$//; print $pwd' $0`
cd $relative_dir
使用符号链接工作,并为我的许多同事工作,无论他们选择的shell类型