I am calling a shell script from a remote location. How do I get the directory that contains the executing shell script (in Windows and Unix-based systems)?
I do not have access to bash on the host system. Git is installed (on the Windows machine) though so I can use its distribution of sh.exe
.
I've followed the advice of https://stackoverflow.com/a/43919044 and have the following:
whatsmydirectory.sh
#!/bin/sh
a="/$0";
echo "$a"
a="${a%/*}";
echo "$a"
a="${a:-.}";
echo "$a"
a="${a##/}/";
echo "$a"
BINDIR=$(cd "$a"; pwd)
echo "$BINDIR"
This works fine on Unix-based systems. However, it doesn't work with Windows.
MacOS
This correctly returns the location of the script /Users/username/Desktop
username@mac Desktop % ./whatsmydirectory.sh
/./whatsmydirectory.sh
/.
/.
./
/Users/username/Desktop
Windows
This returns the current working directory /c
, rather than the location of the script C:\Program Files\Some Program\
.
C:\> C:/"Program Files"/Git/usr/bin/sh.exe "C:\Program Files\Some Program\whatsmydirectory.sh"
/C:\Program Files\Some Program\whatsmydirectory.sh
.
./
/c
How can I modify the shell script such that it works equally well on both Windows and Unix-like hosts?