Bash – how to get main program and current file dir location

Get main program directory location

#!/bin/bash
PROGRAM_DIR="$( cd "$( dirname "$0" )" && pwd)"
In case you have a program main.sh in /opt/tmp which includes utils.sh from /opt/tmp/dir1, then this code will return /opt/tmp as directory.

Get file directory location

#!/bin/bash
CURRENT_FILE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
In case you have a program main.sh in /opt/tmp which includes utils.sh from /opt/tmp/dir1, then this code will return /opt/tmp/dir1 as directory. Note that BASH_SOURCE is an array containing file name of current file and parent files (first element being the current file name and so on).

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments