How do I get the directory where a Bash script is located from within the script itself?

 

To get the directory where a Bash script is located from within the script itself, you can use the dirname command with the special variable $0. Here's an example:

bash
#!/bin/bash # Get the directory where the script is located script_dir=$(dirname "$0") # Print the script directory echo "Script directory: $script_dir"

In this example:

  1. #!/bin/bash is the shebang line that specifies the shell to use (Bash in this case).

  2. dirname "$0" extracts the directory path from the special variable $0, which contains the path of the script itself. The dirname command returns the directory containing the script.

  3. The result is stored in the script_dir variable.

  4. Finally, we print the script directory using echo.

When you run this script, it will print the directory where the script is located. This is useful for cases where you need to refer to other files or resources relative to the script's location.

Comments