views:

1294

answers:

4

How would I get just the current working directory name in a bash script, or even better, just a terminal command.

pwd gives the full path of the current working directory, e.g. '/opt/local/bin' but I only want 'bin'

+1  A: 

Use the basename program. For your case::

% basename $PWD
bin
scrible
A: 

You can use a combination of pwd and basename. E.g.

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename $CURRENT`

echo $BASENAME

exit;
mbelos
Please, no. The backticks create a subshell (thus, a fork operation) -- and in this case, you're using them *twice*! [As an additional, albeit stylistic quibble -- variable names should be lower-case unless you're exporting them to the environment or they're a special, reserved case].
Charles Duffy
and as a second style quibble backtics should be replaced by $(). still forks but more readable and with less excaping needed.
Jeremy Wall
+13  A: 

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:

${PWD##*/}
Charles Duffy
+2  A: 

$ echo ${PWD##*/}

DigitalRoss
The correct answer, but I believe I beat you to it. :)
Charles Duffy
Si. If it were a harder question I would say *GMTA* :-)
DigitalRoss