tags:

views:

1825

answers:

5

In a Windows command script, one can determine the directory path of the currently executing script using %~dp0. For example:

@echo Running from %~dp0

What would be the equivalent in a BASH script?

+6  A: 

For the relative path (i.e. the direct equivalent of Windows' %~dp0):

MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH="`dirname \"$0\"`"              # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

Cheers, V.

vladr
doesn't work on my mac bash.
Mykola Golubyev
what is the problem on your mac bash? works just fine over here on Cygwin, Linux, Solaris, etc., and it must also work on mac
vladr
it only gives the relative path though
anon
$0 gives "-bash" and then dirname argue about "-b" option.
Mykola Golubyev
@Mykola, This is because you are running it directly at the command prompt, not from a script, and because mac is anal about what $0 is at the command prompt (the above works at the command prompt on all other platforms BTW.)
vladr
If you do "exec /bin/bash" you'll then populate $0 with what you want.
Nerdling
If this is bash specifically I'd use `$()` over `\`\``. The only thing that \` has better is POSIX-compatibility.
Daenyth
+1  A: 

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Alex Reynolds
@Rothko, your solution will fail if $0 contains blanks.
vladr
+1  A: 

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"
radoulov
A: 

Vlad's code is overquoted. Should be:

MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`
pooryorick
Your second line has an extra double-quote character.
Eric Seppanen
A: 
echo Running from `dirname $0`
xagyg