Languages
[Edit]
EN

Bash - get current script directory path

8 points
Created by:
Zeeshan-Peel
850

In this short article, we would like to show how to get the currently executed script directory path in Bash.

Quick solution:

#!/bin/bash

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

echo $SCRIPT_DIR;

Notes:

  • no metter from where we will execute script, $SCRIPT_DIR will indicate directory where script is located, e.g. /c/test/script.sh with above script will print /c/text,
  • the solution is not working if last component of the script path is a symlink, but it is enought for most cases.

Screenshot:

Script directory path printed in Bash under Windows.
Script directory path printed in Bash under Windows.

Universal Windows and Linux path formats

If you want to get a solution that returns Windows or Linux formatted path try this solution:

#!/bin/bash

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && (pwd -W 2> /dev/null || pwd))

echo $SCRIPT_DIR;  // Format under Windows:     C:/test
                   // Format under Linux/Unix:  /c/test

 

Alternative solutions

There are other ways how to get executed script directory path, we will focus on 2 of them. The main idea is to get script full path with readlink or realpath command and later extract directory path with dirname.

 

1. readlink based example

That approach doesn't prevent situations when the script is attached as a source (source path/to/script.sh) returning called script path - is enough when we have just one *.sh script.

script.sh file content:

#!/bin/bash

SCRIPT_PATH=`readlink -f "$0"`
SCRIPT_DIR=`dirname "$SCRIPT_PATH"`

echo $SCRIPT_DIR;

Executing from /c location:

$ pwd
/c

$ test/script.sh
/c/test

 

2. realpath based example

That approach doesn't prevent situations when the script is attached as a source (source path/to/script.sh) returning called script path - is enough when we have just one *.sh script.

script.sh file content:

#!/bin/bash

SCRIPT_PATH=`realpath "$0"`
SCRIPT_DIR=`dirname "$SCRIPT_PATH"`

echo $SCRIPT_DIR;

Executing from /c location:

$ pwd
/c

$ test/script.sh
/c/test

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Bash

Bash - get current script directory path
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join