How do I get the path of the directory in which a Bash script is located, inside that script?
For instance, let's say 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
This is Linux specific, but you could use:
For systems having GNU coreutils readlink (eg. linux):
No need to use
BASH_SOURCE
when$0
contains the script filename.You can use $BASH_SOURCE
Note that you need to use #!/bin/bash and not #!/bin/sh since its a bash extension
A slight revision to the solution e-satis and 3bcdnlklvc04a pointed out in their answer
This should still work in all the cases they listed.
EDIT: prevent popd after failed pushd, thanks to konsolebox
This should do it:
Works with symlinks and spaces in path. See man pages for dirname and readlink.
Edit:
From the comment track it seems not to work with Mac OS. I have no idea why that is. Any suggestions?
Here is a POSIX compliant one-liner: