Bash get filename from given path on Linux or Unix

In bash, you can use the basename command to extract the filename from a given path on Linux or Unix. The basename command takes the path as an argument, and returns the filename without the path. Here is an example of how to use the basename command to extract the filename from a given path:

$ filename=$(basename /path/to/file.txt)
$ echo $filename
file.txt

Alternatively, you could use string manipulation techniques to extract the filename from a given path. Here is an example of how you could use the ${variable##*/} parameter expansion to extract the filename:

$ path=/path/to/file.txt
$ filename=${path##*/}
$ echo $filename
file.txt

In this example, the ##*/ parameter expansion operator removes the longest match of */ from the start of the variable, effectively removing the path and leaving only the filename.

Another way to extract the filename from a given path is using the dirname command which returns the path of the file without the file name, then you can use string concatenation to add the file name to the path.

$ path=/path/to/file.txt
$ dir_path=$(dirname "$path")
$ file_name=file.txt
$ echo $dir_path/$file_name
/path/to/file.txt

These are some examples of how you can extract the filename from a given path on a Linux or Unix system using bash. You can choose the one that best suits your needs.

Leave a Comment