Bash scripts will often assume that they are being invoked from the same directory where they are located. The script may use relative paths to configuration files or logs that it expects.
The problem is that one cannot assume that the directory a script lives in is necessarily the one it is being invoked from. In other words, a user might currently be in the /tmp directory, but invoking your script which is located in the /opt directory.
To handle this situation, evaluate the current and script directory using code like below.
SCRIPT_DIR_REL=$(dirname ${BASH_SOURCE[0]}) SCRIPT_DIR_ABS=$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd) CURRENT_DIR=$(pwd) echo "Current directory: $CURRENT_DIR" echo "Relative script dir: $SCRIPT_DIR_REL" echo "Absolute script dir: $SCRIPT_DIR_ABS"
Using these variables, you can either choose to prefix relevant files with the path OR you can ‘cd’ to the script directory if that is what the script expects.
Here is a sample script I have provided on github.
REFERENCES