Languages
[Edit]
EN

Bash - get current script directory path

8 points
Created by:
Kate_C
23330

In this short article we would like to show how to get 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:

Currently executed script directory path in Bash.
Currently executed script directory path in Bash.

Practical examples

There are other ways how to get executed script directory path, we will 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 situation when script is attached as source (source path/to/script.sh) returning called script path - is enought 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 situation when script is attached as source (source path/to/script.sh) returning called script path - is enought 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

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