Get Script Location in Bash Regardless of Location Launched From
Nov 29, 2010 · 2 minute readCategory: php
This is post is now quite old and the the information it contains may be out of date or innacurate.
If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub
However, you may have scripts that are running in a development environment and also a live environment with different folder setups.
To help with portability and remove the requirement to hard code paths, you can use this little snippet
DIR="$( cd "$( dirname "$0" )" && pwd )"
For example, I have a system all running from a folder with one subfolder called processes (where my scripts are located) and another folder called launcher which actually handles the application.
The processes scripts generally launch a sequence of actions in one go.
Here is how I am using the above snippet
#!/bin/bash
DIR="$( cd "$( dirname "$0" )" && pwd )"
cd $DIR
cd ../launcher
pwd
./shellLauncher.php Scraper importCsvFile
./shellLauncher.php Scraper scrapeNewProducts
This script cd’s to the script location first (the processes sub folder) then goes back up the folder structure and into the launcher folder before launching the individual actions that make up this process.