BASH Programming

Reverse of Basename – Bash

In Bash, basename is commonly used to extract the filename from a given path or URL; however, there are situations where you may need to do the opposite, like extracting the directory path from a given file path. This is where the dirname command comes into play, which is the reverse of the basename, this article will explain what is the reverse of basename and how to use it in Bash.

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:

#!/bin/bash
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.

#!/bin/bash
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.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.