Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the last directory of a pwd output

Tags:

bash

unix

pwd

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.

like image 461
Siou Avatar asked Nov 16 '09 20:11

Siou


People also ask

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.

How do I get the current directory in bash?

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.

How do I get the current directory name?

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.

What is the output of the command pwd?

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.


2 Answers

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#.*/##' 
like image 145
mihi Avatar answered Sep 25 '22 19:09

mihi


If you want to do it completely within a bash script without running any external binaries, ${PWD##*/} should work.

like image 33
Teddy Avatar answered Sep 23 '22 19:09

Teddy