This is my (current) favorite bash one-liner. I find myself using it more and more in scripts:
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
This sets SCRIPT_DIR
as the directory the script is located. This is different from this:
SCRIPT_DIR=$(pwd)
Which sets SCRIPT_DIR
to where the script is executing.
For instance if we have a bash script called print_current_directory.sh
in ~/files/scripts
:
#!/bin/bash
echo $(pwd)
echo $( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
If we call the script from a ~/files
directory we will get:
$ ./scripts/print_current_directory.sh
/home/files
/home/files/scripts
This can be very handy in scripts run in automated processes.