Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last part of dirname in Bash

Suppose I have a file /from/here/to/there.txt, and want to get only the last part of its dirname to instead of /from/here/to, what should I do?

like image 714
eggplantelf Avatar asked Apr 18 '14 21:04

eggplantelf


People also ask

How do I get the last string in bash?

To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.

What does dirname do in bash?

What is a bash dirname command? Dirname is a built-in command on Linux and Unix-like OSes; it is used to identify paths in shell scripts. Simply, dirname will remove the last part of a filename, after the last forward-slash (/), and print the remaining command as the name of the directory where that file is saved.

How do I find the last directory in Linux?

To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -"

How do I get the last directory name in Unix?

How do I get directory name from its path on a Linux or Unix-like system? [/donotprint]In other words, you can extract the directory name using dirname command.


2 Answers

You can use basename even though it's not a file. Strip off the file name using dirname, then use basename to get the last element of the string:

dir="/from/here/to/there.txt" dir="$(dirname $dir)"   # Returns "/from/here/to" dir="$(basename $dir)"  # Returns just "to" 
like image 151
David W. Avatar answered Oct 19 '22 15:10

David W.


The opposite of dirname is basename:

basename "$(dirname "/from/here/to/there.txt")" 
like image 29
that other guy Avatar answered Oct 19 '22 15:10

that other guy