Menu Close

How to determine the location of a script from within the script


When developing scripts, it is sometimes necessary to determine the absolute location of the script within the script, so that relative paths may be defined. For example, if a script writes logs and data files to different directories relative to the location of the script, you need to determine the location of the script, irrespective of from where it’s executed. Of course, you can hard code this value in the script, but doing so requires you to change the variable whenever you change the location of the script.



(1) Bash Shell:

scriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

(2) Python

from pathlib import *
import sys
scriptDir = Path((PurePath(sys.argv[0]).parent)).resolve()

LAST UPDATED: 30-Jan-2021


(1) The How-To above describes a successful method of implementation. It may or may not be the best method of implementation. If you know of a better implementation or spot an error in the implementation above, kindly make readers aware via comments on this post.

(2) Your rating of this post will be much appreciated. 

VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *