Rize S. answered 03/23/23
Senior IT Certified Trainer, IT Developer & DBA Administrator
You can use the dirname command to find out the directory where the script file resides. Here's an example of how you can change the current directory to the directory where the script file resides:
#!/bin/bash
# get the directory where the script file resides
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# change to the script directory
cd "$SCRIPT_DIR"
# now you can use paths related to the script directory
In this example, the cd command is used to change the current directory to the directory where the script file resides. The $(dirname "$0") expression gets the directory path where the script file is located, and the cd command changes the current directory to that path.
The pwd command is used to get the full path of the directory where the script file resides. This is important because the dirname command may return a relative path.
The "$SCRIPT_DIR" variable can then be used to refer to paths relative to the script directory.
Note that it's important to double-quote the variables used in the cd command to handle paths with spaces or other special characters correctly.