Skip to content
TrySitePrice

Bash Script: Find Out In What Directory Script Is Stored Under Unix Or Linux

Best/Tutorial

You can use the following line of code in a bash script to determine the directory in which the script is stored:

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

Here's how it works:

  • dirname "$0" returns the directory component of the script's file path.
  • cd "$(dirname "$0")" && pwd changes to the directory and prints the absolute path to it.
  • The output of the pwd command is stored in the SCRIPT_DIR variable.
rnYou can then use the SCRIPT_DIR variable in your script to refer to the directory where the script is stored, for example, to access other files in the same directory.

For example:

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "The script is stored in: $SCRIPT_DIR"

This script will print the absolute path to the directory where the script is stored.