How do I extract the last directory of a pwd output? I don't want to use any knowledge of how many levels there are in the directory structure. If I wanted to use that, I could do something like:
> pwd /home/kiki/dev/my_project > pwd | cut -d'/' -f5 my_project
But I want to use a command that works regardless of where I am in the directory structure. I assume there is a simple command to do this using awk or sed.
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.
Print Current Working Directory ( pwd ) To print the name of the current working directory, use the command pwd . As this is the first command that you have executed in Bash in this session, the result of the pwd is the full path to your home directory.
To determine the exact location of the current directory at a shell prompt and type the command pwd. This example shows that you are in the user sam's directory, which is in the /home/ directory. The command pwd stands for print working directory.
The pwd command writes to standard output the full path name of your current directory (from the root directory). All directories are separated by a / (slash). The root directory is represented by the first /, and the last directory named is your current directory.
Are you looking for basename or dirname?
Something like
basename "`pwd`"
should be what you want to know.
If you insist on using sed
, you could also use
pwd | sed 's#.*/##'
If you want to do it completely within a bash script without running any external binaries, ${PWD##*/}
should work.
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