Linux

Bash get basename of filename or directory name

I need to extract file basename in bash running on Linux. How can I use bash to get basename of filename or directory name for given path?

Introduction: One can extract filename and extension in bash shell using built-in commands or external commands. The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. See “How To Use Bash Parameter Substitution Like A Pro” for more info. This page shows to remove file basename without path and extension in bash using various methods.

Bash Get Basename of Filename or Directory Name

To extract filename and extension in Bash use any one of the following method:

  1. basename /path/to/file.tar.gz .gz – Strip directory and suffix from filenames
  2. ${VAR%pattern} – Remove file extension
  3. ${VAR#pattern} – Delete from shortest front pattern

Let us see some example in bash to get basename of filename.

Bash get filename and extension

To just get filename from a given path:

Get filename without using basename command

The syntax is:

Bash Get Basename of Filename or Directory Name on Linux and Unix

Get running script name using bash parameter

The $0 will provide full path for currently running script. To extract that name only:

Bash get a file extension

Try the following examples:

Extract file basename without path and extension in bash

How to get the basename from the full filename path in bash

Use any one of the following syntax:

Let us just get the first part of the $file when you know that .enc is extension:

Script example to extract filename and extension in Bash

Conclusion

You just learned how to get the basename and extension from the full filename when using Bash shell running on a Linux or Unix-like system.

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close