Skip to content
Fix Code Error

How can I get the source directory of a Bash script from within the script itself?

March 13, 2021 by Code Error
Posted By: Jim Robert

How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Solution

#!/bin/bash

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

is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.

It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

This last one will work with any combination of aliases, source, bash -c, symlinks, etc.

Beware: if you cd to a different directory before running this snippet, the result may be incorrect!

Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.

To understand how it works, try running this more verbose form:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  TARGET="$(readlink "$SOURCE")"
  if [[ $TARGET == /* ]]; then
    echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
    SOURCE="$TARGET"
  else
    DIR="$( dirname "$SOURCE" )"
    echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
    SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
  fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
if [ "$DIR" != "$RDIR" ]; then
  echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"

And it will print something like:

SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
Answered By: Anonymous

Related Articles

  • Jetpack Compose and Hilt Conflict
  • Android- Error:Execution failed for task…
  • "Non-resolvable parent POM: Could not transfer…
  • Execution failed for task…
  • Exception trying to get folder in MailKit, but not…
  • ADB - Android - Getting the name of the current activity
  • Non-resolvable parent POM for Could not find…
  • How do you list volumes in docker containers?
  • Apply a EWMA rolling window function in Pandas but…
  • What are the best JVM settings for Eclipse?
  • Fix top buttons on scroll of list below
  • When I'm testing a web app by JUnit and Mockito I…
  • Error:Execution failed for task…
  • Get parent of current directory from Python script
  • Mount current directory as a volume in Docker on Windows 10
  • Gradle: Execution failed for task ':processDebugManifest'
  • npm install error in vue
  • webpack-dev-server npm run dev throwing TypeError:…
  • Aurelia view-model without a view?
  • What is a NullReferenceException, and how do I fix it?
  • Reliable way for a Bash script to get the full path…
  • Webpack dev server for vue-cli: Error spawn EACCES
  • Eclipse will not start and I haven't changed anything
  • Pandas how to split vlaues of every column based on colon
  • useEffect Error: Minified React error #321 (GTM…
  • Docker compose fails to start a service with an…
  • Unions Data.Map singletons inside an IO
  • Creating a custom counter in Spark based on…
  • How do I get the current working directory when…
  • Get current directory name (without full path) in a…
  • Why am I getting a "401 Unauthorized" error in Maven?
  • How to get the parent dir location
  • Combining Ember Table with Ember Data
  • How to assign the output of a Bash command to a variable?
  • Issue: C compiler used for C++ in CMake | CMake + git
  • Java 6 Unsupported major.minor version 51.0
  • Extract a part of the filepath (a directory) in Python
  • Retrieve WordPress root directory path?
  • os.path.dirname(__file__) returns empty
  • android studio 0.4.2: Gradle project sync failed error
  • Change the location of the ~ directory in a Windows…
  • Maven is not working in Java 8 when Javadoc tags are…
  • File changed listener in Java
  • Problems using Maven and SSL behind proxy
  • Why does `which` print out a script?
  • My Application Could not open ServletContext resource
  • One to many relationship in two JSON arrays, lookup…
  • Problem with volley POST and response null from the…
  • Temporary zip two temporary files
  • How to install Intellij IDEA on Ubuntu?
  • What is the GAC in .NET?
  • Unable to Build using MAVEN with ERROR - Failed to…
  • How do I use Ruby for shell scripting?
  • The null object does not have a method []=
  • Unable to compile simple Java 10 / Java 11 project…
  • Relative paths based on file location instead of…
  • How to backup a local Git repository?
  • Plugin…
  • configure: error: C compiler cannot create executables
  • Trying to read files in directory, directory just…
  • How can I move all the files from one folder to…
  • Deploying Maven project throws…
  • jmxterm: "Unable to create a system terminal" inside…
  • How to run a shell script on a Unix console or Mac terminal?
  • Worker Script Failing to Load for Vue Webpack Built App
  • How to properly do JSON API GET requests and assign…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Playing HTML5 video on fullscreen in android webview
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Calculate a count of groupby rows that occur within…
  • What's the best way to get the last element of an…
  • How to change an application icon programmatically…
  • Mipmap drawables for icons
  • Can't install via pip because of egg_info error
  • easiest way to extract Oracle form xml format data
  • Smart way to truncate long strings
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Add to PATH from Laravel Sail Dockerfile
  • Getting a 'source: not found' error when using…
  • adding noise to a signal in python
  • Angular 2 router no base href set
  • How do I move all the file paths in an array to one…
  • java.lang.OutOfMemoryError: Java heap space in Maven
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • Clear Cache in Android Application programmatically
  • Failed to execute goal…
  • Issue with iron-ajax request
  • Get current working directory in a Qt application
  • Logging best practices
  • Correctly configure webpack-dev-middleware with…
  • setting JAVA_HOME & CLASSPATH in CentOS 6
  • In R, how to find a file located in any parent…
  • How do I get the path of the current executed file…
  • Aurelia/Karma/Istanbul Cannot read property 'skip'…
  • Bash Script : what does #!/bin/bash mean?
  • Disable-web-security in Chrome 48+
  • Merge list of results into a single variable with Python
  • Using IS NULL or IS NOT NULL on join conditions -…
  • Compiling Java 7 code via Maven
  • How do I echo and send console output to a file in a…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to import other Python files?

Next Post:

How to download Xcode DMG or XIP file?

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error