我有一个Bash脚本,需要知道它的完整路径。我试图找到一种广泛兼容的方式来做到这一点,而不会以相对或时髦的路径结束。我只需要支持Bash,不支持sh, csh等。

到目前为止,我发现:

The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via dirname $0, which is fine, but that may return a relative path (like .), which is a problem if you want to change directories in the script and have the path still point to the script's directory. Still, dirname will be part of the puzzle. The accepted answer to Bash script absolute path with OS X (OS X specific, but the answer works regardless) gives a function that will test to see if $0 looks relative and if so will pre-pend $PWD to it. But the result can still have relative bits in it (although overall it's absolute) — for instance, if the script is t in the directory /usr/bin and you're in /usr and you type bin/../bin/t to run it (yes, that's convoluted), you end up with /usr/bin/../bin as the script's directory path. Which works, but... The readlink solution on this page, which looks like this: # Absolute path to this script. /home/user/bin/foo.sh SCRIPT=$(readlink -f $0) # Absolute path this script is in. /home/user/bin SCRIPTPATH=`dirname $SCRIPT` But readlink isn't POSIX and apparently the solution relies on GNU's readlink where BSD's won't work for some reason (I don't have access to a BSD-like system to check).

有很多种方法,但都有注意事项。

还有什么更好的办法呢?“更好”的意思是:

Gives me the absolute path. Takes out funky bits even when invoked in a convoluted way (see comment on #2 above). (E.g., at least moderately canonicalizes the path.) Relies only on Bash-isms or things that are almost certain to be on most popular flavors of *nix systems (GNU/Linux, BSD and BSD-like systems like OS X, etc.). Avoids calling external programs if possible (e.g., prefers Bash built-ins). (Updated, thanks for the heads up, wich) It doesn't have to resolve symlinks (in fact, I'd kind of prefer it left them alone, but that's not a requirement).


当前回答

我已经成功地使用了下面的方法一段时间(不是在OS X上),它只使用一个内置的shell,并处理'source foobar.sh'的情况,就我所见。

下面的示例代码的一个问题是,函数使用$PWD,在函数调用时,$PWD可能正确,也可能不正确。所以这需要处理。

#!/bin/bash

function canonical_path() {
  # Handle relative vs absolute path
  [ ${1:0:1} == '/' ] && x=$1 || x=$PWD/$1
  # Change to dirname of x
  cd ${x%/*}
  # Combine new pwd with basename of x
  echo $(pwd -P)/${x##*/}
  cd $OLDPWD
}

echo $(canonical_path "${BASH_SOURCE[0]}")

type [
type cd
type echo
type pwd

其他回答

获取shell脚本的绝对路径

它没有在readlink中使用-f选项,因此它应该在BSD/Mac OS X上工作。

支持

source ./script(当被。点运算符) 绝对路径/path/to/script 相对路径,比如。/script /道路/ dir1 / . . / dir2 / dir3 / . . /脚本 当从symlink调用时 当符号链接嵌套eg) foo->dir1/dir2/bar bar->./../能源部doe - >脚本 当调用者更改脚本名称时

我正在寻找这段代码不能工作的极端情况。请让我知道。

Code

pushd . > /dev/null
SCRIPT_PATH="${BASH_SOURCE[0]}";
while([ -h "${SCRIPT_PATH}" ]); do
    cd "`dirname "${SCRIPT_PATH}"`"
    SCRIPT_PATH="$(readlink "`basename "${SCRIPT_PATH}"`")";
done
cd "`dirname "${SCRIPT_PATH}"`" > /dev/null
SCRIPT_PATH="`pwd`";
popd  > /dev/null
echo "srcipt=[${SCRIPT_PATH}]"
echo "pwd   =[`pwd`]"

已知的政务

脚本必须在磁盘的某个地方。让它通过网络。如果您试图从PIPE运行这个脚本,它将无法工作

wget -o /dev/null -O - http://host.domain/dir/script.sh |bash

从技术上讲,它是没有定义的。实际上,没有明智的方法来检测这一点。(协进程不能访问父进程的环境。)

易于阅读?下面是一个替代方案。它忽略了符号链接

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

echo -n "current "
pwd
echo script $currentDir

自从几年前我发布了上面的答案,我已经发展了我的实践,使用这个linux特定的范例,它正确地处理符号链接:

ORIGIN=$(dirname $(readlink -f $0))

您可以尝试定义以下变量:

CWD="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"

或者你可以在Bash中尝试以下函数:

realpath () {
  [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

这个函数有一个参数。如果参数已经有一个绝对路径,则打印它,否则打印$PWD变量+文件名参数(不带。/前缀)。

相关:

Bash脚本绝对路径与OS X 从脚本本身中获取Bash脚本的源目录

被接受的解决方案(对我来说)不方便“来源”: 如果你从“来源../..”/yourScript", $0将是"bash"!

下面的函数(对于bash >= 3.0)给出了正确的路径,但是脚本可能会被调用(直接或通过源代码,使用绝对路径或相对路径): (这里的“正确路径”指的是被调用脚本的完整绝对路径,即使是从另一个路径直接调用,也可以使用“source”)

#!/bin/bash
echo $0 executed

function bashscriptpath() {
  local _sp=$1
  local ascript="$0"
  local asp="$(dirname $0)"
  #echo "b1 asp '$asp', b1 ascript '$ascript'"
  if [[ "$asp" == "." && "$ascript" != "bash" && "$ascript" != "./.bashrc" ]] ; then asp="${BASH_SOURCE[0]%/*}"
  elif [[ "$asp" == "." && "$ascript" == "./.bashrc" ]] ; then asp=$(pwd)
  else
    if [[ "$ascript" == "bash" ]] ; then
      ascript=${BASH_SOURCE[0]}
      asp="$(dirname $ascript)"
    fi  
    #echo "b2 asp '$asp', b2 ascript '$ascript'"
    if [[ "${ascript#/}" != "$ascript" ]]; then asp=$asp ;
    elif [[ "${ascript#../}" != "$ascript" ]]; then
      asp=$(pwd)
      while [[ "${ascript#../}" != "$ascript" ]]; do
        asp=${asp%/*}
        ascript=${ascript#../}
      done
    elif [[ "${ascript#*/}" != "$ascript" ]];  then
      if [[ "$asp" == "." ]] ; then asp=$(pwd) ; else asp="$(pwd)/${asp}"; fi
    fi  
  fi  
  eval $_sp="'$asp'"
}

bashscriptpath H
export H=${H}

关键是检测“source”大小写,并使用${BASH_SOURCE[0]}返回实际的脚本。

再次考虑这个问题:在这个线程中引用了一个非常流行的解决方案,它的起源在这里:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

我一直没有使用这种解决方案,因为使用了dirname——它可能会带来跨平台的困难,特别是在出于安全原因需要锁定脚本的情况下。但是作为一个纯Bash的替代品,如何使用:

DIR="$( cd "$( echo "${BASH_SOURCE[0]%/*}" )" && pwd )"

这是一个选择吗?