Reverse of Basename
The dirname command is used to extract the directory path from a given file path as this command takes a single argument, which is the file path that you want to extract the directory path from. Here is an example Bash script that uses dirname to extract the directory path from a file path:
path="/home/aaliyan/Documents/myfiles/bashfile1.sh"
dir=$(dirname "$path")
echo "Directory path: $dir"
In this script, we define a variable path that contains a file path and then use the dirname command to extract the directory path from the path variable and store it in a new variable called dir. Finally, we use the echo command to print the directory path to the console, when you run this script, you should see the following output:
The dirname command can also be used to extract the directory path of a file that is located in the same directory as your script, you could use the realpath command.
path="./bashfile1.sh"
dir=$(realpath $(dirname "$path"))
echo "Directory path: $dir"
The script first sets the path variable to the relative file path of bashfile1.sh and next the script uses the dirname command to extract the directory path from the file path, this returns a relative directory path.
To convert the relative path to an absolute path, the script uses the realpath command, which takes the relative path as an argument and returns the absolute path. Finally, the script prints the absolute directory path using the echo command:
Conclusion
The dirname command in Bash is used to extract the directory path from a given file path, this command is useful in situations where you need to manipulate file paths in your Bash scripts. By combining dirname with other Bash utilities like basename, you can easily manipulate file paths and perform complex operations on your files.