Can I get the absolute path to the current script

2019-02-04 11:27发布

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, can I programmatically inside that script discover /opt/scripts/myscript.ksh ?

Thanks,

12条回答
不美不萌又怎样
2楼-- · 2019-02-04 11:31

This is what I did:

if [[ $0 != "/"* ]]; then
  DIR=`pwd`/`dirname $0`
else
  DIR=`dirname $0`
fi
查看更多
Evening l夕情丶
3楼-- · 2019-02-04 11:34

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..

查看更多
女痞
4楼-- · 2019-02-04 11:34

How the script was called is stored in the variable $0. You can use readlink to get the absolute file name:

readlink -f "$0"
查看更多
做自己的国王
5楼-- · 2019-02-04 11:36

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

查看更多
女痞
6楼-- · 2019-02-04 11:37

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"

查看更多
Melony?
7楼-- · 2019-02-04 11:41

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 )
查看更多
登录 后发表回答