'How to get script directory in POSIX sh?

I have the following code in my bash script. Now I wanna use it in POSIX sh. How can I convert it?

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


Solution 1:[1]

@City responded that

DIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )

works. I used it too.
I found the command at https://stackoverflow.com/questions/760110/can-i-get-the-absolute-path-to-the-cu??rrent-script-in-kornshell.

Solution 2:[2]

if      OLDPWD=/dev/fd/0 \
        cd - && ls -lLidFH ?
then    cd . <8
fi      </proc/self/fd 8<. 9<$0

there. that should enable you to change directpry through some magic links as file descriptors.

setting $OLDPWD pre-cd exports the value for the duration of the one change directory (note: cd can have residual effects on hash tables, but the only sh about which i am aware that actually males any good use of these is kevin ahlmquists - and since herbert xu - dash, and maybe some bsd stuff, but what do i know?) but does not carry over any cd exports as a result of the change.

thus, $OLDPWD does not change, actually, and if it had any value at all this remains as was. $PWD is changed as a result of the first cd, and the value becomes /dev/fd/0 which points to /proc/self/fd, where a list of file descriptors for our process should be in ., to include whatever $0 is on ./2.

so we do an ls ... ? and have a look at all of the wonderful info we can get, and we go whence we came.

yay!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 mikeserv