Reliable way for a bash script to get the full path to itself?

This question already has an answer here:

  • Getting the source directory of a Bash script from within 50 answers

  • Here's what I've come up with (edit: plus some tweaks provided by sfstewman, levigroker, Kyle Strand, and Rob Kennedy), that seems to mostly fit my "better" criteria:

    SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
    

    That SCRIPTPATH line seems particularly roundabout, but we need it rather than SCRIPTPATH=`pwd` in order to properly handle spaces and symlinks.

    Note also that esoteric situations, such as executing a script that isn't coming from a file in an accessible file system at all (which is perfectly possible), is not catered to there (or in any of the other answers I've seen).


    I'm surprised that the realpath command hasn't been mentioned here. My understanding is that it is widely portable / ported.

    Your initial solution becomes:

    SCRIPT=`realpath $0`
    SCRIPTPATH=`dirname $SCRIPT`
    

    And to leave symbolic links unresolved per your preference:

    SCRIPT=`realpath -s $0`
    SCRIPTPATH=`dirname $SCRIPT`
    

    The simplest way that I have found to get a full canonical path in bash is to use cd and pwd :

    ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
    

    Using ${BASH_SOURCE[0]} instead of $0 produces the same behavior regardless of whether the script is invoked as <name> or source <name>

    链接地址: http://www.djcxy.com/p/1670.html

    上一篇: 我如何知道Bash脚本中的脚本文件名?

    下一篇: bash脚本获得完整路径的可靠方法?