I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files.
Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?
Standard Variables There are a number of standard variables, some less easy/obvious, for example %~dp0 ! So let's break this down a bit, "%~" is the special key that gets us started, "d" is for driver letter, "p" is for path and 0 (zero) means the script file itself. So, create the following in "C:\Temp\TestScript.cmd"
It means "all the parameters in the command line".
cd /d %~dp0 will change the path to the same, where the batch file resides.
%0 is the name of the batch file. %~n0 Expands %0 to a file Name without file extension.
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.SCRIPTDIR
.cd -
".Yes, you can! It's in the arguments. :)
look at
${0}
combining that with
{$var%Pattern}
Remove from $var the shortest part of $Pattern that matches the back end of $var.
what you want is just
${0%/*}
I recommend the Advanced Bash Scripting Guide (that is also where the above information is from). Especiall the part on Converting DOS Batch Files to Shell Scripts might be useful for you. :)
If I have misunderstood you, you may have to combine that with the output of "pwd". Since it only contains the path the script was called with! Try the following script:
#!/bin/bash
called_path=${0%/*}
stripped=${called_path#[^/]*}
real_path=`pwd`$stripped
echo "called path: $called_path"
echo "stripped: $stripped"
echo "pwd: `pwd`"
echo "real path: $real_path
This needs some work though. I recommend using Dave Webb's approach unless that is impossible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With