Bash

Get last dirnamefilename in a file path argument in Bash

27 September 2026 · 5 min read

Get last dirnamefilename in a file path argument in Bash

Navigating file paths is a fundamental aspect of bash scripting. Whether you’re writing complex automation scripts or simply trying to extract information from a file path, knowing how to efficiently retrieve the last directory name or filename is crucial. This post delves into various techniques for getting the last dirname/filename in a bash file path argument, providing you with the tools and knowledge to streamline your scripts and boost your command-line proficiency.

Using basename

The basename command is a powerful utility specifically designed to extract the filename from a given path. It effectively strips away the directory component, leaving you with just the filename. This is particularly useful when you need to process a large number of files or when you only need the filename for logging or reporting purposes. For example, basename /path/to/my/file.txt returns file.txt.

basename also handles edge cases gracefully. If you provide a path ending with a slash (e.g., /path/to/my/directory/), it will correctly return the last directory name (directory in this case). This consistent behavior makes it a reliable tool for diverse scripting scenarios.

Beyond its basic functionality, basename offers a -s option to remove a suffix from the filename. This can be useful for tasks like removing file extensions. For instance, basename -s .txt /path/to/my/file.txt returns file. This added flexibility makes basename a versatile tool in your bash scripting arsenal.

Using dirname

The dirname command is the counterpart to basename. While basename extracts the filename, dirname extracts the directory component of a given path. This is essential for tasks like changing directories or identifying the location of a file within a complex directory structure.

For example, dirname /path/to/my/file.txt returns /path/to/my. This allows you to isolate the directory portion and use it in other commands or scripts.

Combining dirname with other commands can create powerful workflows. For example, you could use cd $(dirname /path/to/my/file.txt) to navigate to the directory containing file.txt. This dynamic approach makes your scripts more adaptable and less reliant on hardcoded paths.

Parameter Expansion

Bash provides built-in parameter expansion features that offer a highly efficient way to manipulate strings, including file paths. This method avoids the overhead of calling external commands like basename or dirname, resulting in faster script execution, especially when dealing with a large number of paths.

To extract the filename, you can use ${variable/}. This removes the longest matching prefix pattern / from the variable’s value. For instance, if variable=/path/to/my/file.txt, ${variable/} will return file.txt.

Similarly, extracting the directory component can be achieved using ${variable%/}. This removes the shortest matching suffix pattern /. Using the same example, ${variable%/} returns /path/to/my.

Practical Examples

Let’s illustrate these concepts with real-world scenarios. Imagine you have a script that processes log files stored in a directory. Using basename, you could easily extract the filename from each log file path for reporting purposes. This helps you identify which files were processed without the clutter of the full path.

Another example involves creating backup directories. Using dirname in conjunction with mkdir allows you to dynamically create backup directories based on the original file’s location. This ensures that your backups are organized and easy to manage.

Finally, consider a script that needs to quickly process a massive number of file paths. Leveraging parameter expansion for extracting filenames can significantly improve performance compared to using external commands. This optimization can be crucial for time-sensitive operations.

“Efficient path manipulation is the hallmark of a well-written bash script.” - Bash Scripting Guru

  • Mastering these techniques will make your scripts more robust and efficient.
  • Practice using basename, dirname, and parameter expansion with various file paths to solidify your understanding.
  1. Identify the file path you want to process.
  2. Choose the appropriate method (basename, dirname, or parameter expansion).
  3. Implement the chosen method in your bash script.

Learn more about Bash ScriptingExtracting the last part of a file path is a common task in bash scripting. Whether you need the filename or the directory, the tools and techniques discussed here provide efficient solutions.

![Infographic about Bash File Path Manipulation]([infographic placeholder])

FAQ

Q: What’s the difference between basename and ${variable/}?

A: While both extract the filename, ${variable/} uses parameter expansion and is generally faster, especially within loops.

By understanding and implementing these techniques, you’ll elevate your bash scripting skills and become more proficient at manipulating file paths. Explore the linked resources and experiment with different scenarios to further enhance your knowledge and discover advanced applications of these fundamental commands. Start optimizing your scripts today and unlock the full potential of bash!

Explore related topics such as shell scripting, command-line utilities, and file system navigation to further expand your knowledge and refine your scripting abilities.

Question & Answer :
I’m trying to write a post-commit hook for SVN, which is hosted on our development server. My goal is to try to automatically checkout a copy of the committed project to the directory where it is hosted on the server. However I need to be able to read only the last directory in the directory string passed to the script in order to checkout to the same sub-directory where our projects are hosted.

For example if I make an SVN commit to the project “example”, my script gets “/usr/local/svn/repos/example” as its first argument. I need to get just “example” off the end of the string and then concat it with another string so I can checkout to “/server/root/example” and see the changes live immediately.

basename does remove the directory prefix of a path:

$ basename /usr/local/svn/repos/example example $ echo "/server/root/$(basename /usr/local/svn/repos/example)" /server/root/example