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

前端 未结 12 758
粉色の甜心
粉色の甜心 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 07:04

    I upgraded the Edward Staudt's answer, to be able to deal with absolute-path symbolic links, and with chains of links too.

    DZERO=$0
    while true; do
      echo "Trying to find real dir for script $DZERO"
      CPATH=$( cd -P -- "$(dirname -- "$(command -v -- "$DZERO")")" && pwd -P )
      CFILE=$CPATH/`basename $DZERO`
      if [ `ls -dl $CFILE | grep -c "^l" 2>/dev/null` -eq 0 ];then
        break
      fi
      LNKTO=`ls -ld $CFILE | cut -d ">" -f2 | tr -d " " 2>/dev/null`
      DZERO=`cd $CPATH ; command -v $LNKTO`
    done
    

    Ugly, but works... After run this, the path is $CPATH and the file is $CFILE

提交回复
热议问题