Can I get the absolute path to the current script in KornShell?

前端 未结 12 565
粉色の甜心
粉色の甜心 2020-12-29 06:26

Is it possible to find out the full path to the script that is currently executing in KornShell (ksh)?

i.e. if my script is in /opt/scripts/myscript.ksh

相关标签:
12条回答
  • 2020-12-29 06:45

    Well it took me a while but this one is so simple it screams.

    _SCRIPTDIR=$(cd $(dirname $0);echo $PWD)
    

    since the CD operates in the spawned shell with $() it doesn't affect the current script.

    0 讨论(0)
  • 2020-12-29 06:48

    In korn shell, all of these $0 solutions fail if you are sourcing in the script in question. The correct way to get what you want is to use $_

    $ cat bar
    
    echo dollar under is $_
    echo dollar zero is $0
    
    $ ./bar
    
    dollar under is ./bar
    dollar zero is ./bar
    
    $ . ./bar
    dollar under is bar
    dollar zero is -ksh
    

    Notice the last line there? Use $_. At least in Korn. YMMV in bash, csh, et al..

    0 讨论(0)
  • 2020-12-29 06:51

    Try using this:

    dir = $(dirname $0)
    
    0 讨论(0)
  • 2020-12-29 06:52

    You could use:

    ## __SCRIPTNAME - name of the script without the path
    ##
    typeset -r __SCRIPTNAME="${0##*/}"
    
    ## __SCRIPTDIR - path of the script (as entered by the user!)
    ##
    __SCRIPTDIR="${0%/*}"
    
    ## __REAL_SCRIPTDIR - path of the script (real path, maybe a link)
    ##
    __REAL_SCRIPTDIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
    
    0 讨论(0)
  • 2020-12-29 06:52

    This works also, although it won't give the "true" path if it's a link. It's simpler, but less exact.

    SCRIPT_PATH="$(whence ${0})"
    
    0 讨论(0)
  • 2020-12-29 06:52

    Using $_ provides the last command.

    >source my_script
    

    Works if I issue the command twice:

    >source my_script
    >source my_script
    

    If I use a different sequence of commands:

    >who
    >source my_script
    

    The $_ variable returns "who"

    0 讨论(0)
提交回复
热议问题