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:
#!/bin/bash
is the shebang line that specifies the shell to use (Bash in this case).dirname "$0"
extracts the directory path from the special variable$0
, which contains the path of the script itself. Thedirname
command returns the directory containing the script.The result is stored in the
script_dir
variable.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
Post a Comment