The problem (for you) with $0
is that it is set to whatever command line was use to invoke the script, not the location of the script itself. This can make it difficult to get the full path of the directory containing the script which is what you get from %~dp0
in a Windows batch file.
For example, consider the following script, dollar.sh
:
#!/bin/bash
echo $0
If you'd run it you'll get the following output:
# ./dollar.sh
./dollar.sh
# /tmp/dollar.sh
/tmp/dollar.sh
So to get the fully qualified directory name of a script I do the following:
cd `dirname $0`
SCRIPTDIR=`pwd`
cd -
This works as follows:
cd
to the directory of the script, using either the relative or absolute path from the command line.
- Gets the absolute path of this directory and stores it in
SCRIPTDIR
.
- Goes back to the previous working directory using "
cd -
".