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


当前回答

我发现的最有效的方法之一是

#!/bin/sh
relative_dir=`perl -e 'use Cwd "realpath";$pwd = realpath(shift); $pwd =~ s/\/[^\/]*$//; print $pwd' $0`
cd $relative_dir

使用符号链接工作,并为我的许多同事工作,无论他们选择的shell类型

其他回答

正如marko所言:

BASEDIR=$(dirname $0)
echo $BASEDIR

除非你在脚本所在的目录中执行脚本,在这种情况下,你会得到一个值'。'

要解决这个问题,请使用:

current_dir=$(pwd)
script_dir=$(dirname $0)

if [ $script_dir = '.' ]
then
script_dir="$current_dir"
fi

现在可以在整个脚本中使用变量current_dir来引用脚本目录。然而,这可能仍然有符号链接的问题。

这应该能奏效:

echo `pwd`/`dirname $0`

它可能看起来很丑,这取决于它是如何被调用和cwd,但应该得到你需要去的地方(或者你可以调整字符串,如果你关心它的外观)。

So many answers, all plausible, each with pro's and con's & slightly differeing objectives (which should probably be stated for each). Here's another solution that meets a primary objective of both being clear and working across all systems, on all bash (no assumptions about bash versions, or readlink or pwd options), and reasonably does what you'd expect to happen (eg, resolving symlinks is an interesting problem, but isn't usually what you actually want), handle edge cases like spaces in paths, etc., ignores any errors and uses a sane default if there are any issues.

每个组件都存储在一个单独的变量中,您可以单独使用:

# script path, filename, directory
PROG_PATH=${BASH_SOURCE[0]}      # this script's name
PROG_NAME=${PROG_PATH##*/}       # basename of script (strip path)
PROG_DIR="$(cd "$(dirname "${PROG_PATH:-$PWD}")" 2>/dev/null 1>&2 && pwd)"

假设您正在使用bash

#!/bin/bash

current_dir=$(pwd)
script_dir=$(dirname "$0")

echo $current_dir
echo $script_dir

这个脚本应该打印您所在的目录,然后是脚本所在的目录。例如,当使用/home/mez/中的脚本从/调用它时,它输出

/
/home/mez

请记住,当从命令的输出为变量赋值时,请将命令包装在$(and)中—否则将得不到所需的输出。

基本版:

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")")"