Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the path of the executing BASH script [duplicate]

Tags:

bash

People also ask

How do I get the path of a bash script?

The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via dirname $0 , which is fine, but that may return a relative path (like . ), which is a problem if you want to change directories in the script and have the path still point to the script's ...

How do I get the shell path?

To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory. The command pwd stands for print working directory.

How do I change the path of a bash script?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/. bashrc, or ~/.


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"

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.


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"

Vlad's code is overquoted. Should be:

MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`

echo Running from `dirname $0`