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?
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 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.
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 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.
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"
The opposite of dirname
is basename
:
basename "$(dirname "/from/here/to/there.txt")"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With