Languages
[Edit]
EN

Bash - get script directory path

5 points
Created by:
Kate_C
19580

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

Quick solution:

#!/bin/bash

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

echo $SCRIPT_DIR;

Note: 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.

Screenshot:

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

Practical examples

There is few 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

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

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

â€ïžđŸ’» 🙂

Join