Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of %~dp0 in sh

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?

like image 389
paulo.albuquerque Avatar asked Oct 16 '08 09:10

paulo.albuquerque


People also ask

What does %~ dp0 mean in batch file?

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"

What does %~ mean in a batch file?

It means "all the parameters in the command line".

What does CD d %~ dp0 do?

cd /d %~dp0 will change the path to the same, where the batch file resides.

What is n0 in batch file?

%0 is the name of the batch file. %~n0 Expands %0 to a file Name without file extension.


2 Answers

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:

  1. cd to the directory of the script, using either the relative or absolute path from the command line.
  2. Gets the absolute path of this directory and stores it in SCRIPTDIR.
  3. Goes back to the previous working directory using "cd -".
like image 175
Dave Webb Avatar answered Oct 10 '22 11:10

Dave Webb


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.

like image 35
Sarien Avatar answered Oct 10 '22 09:10

Sarien