Bash - Get Current Directory or Folder Name (Without Full Path) In Bash Script

Viewed 850630

How could I retrieve the current working directory/folder 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

Thanks.

21 Answers

Use:

basename "$PWD"

OR

IFS=/ 
var=($PWD)
echo ${var[-1]} 

Turn the Internal Filename Separator (IFS) back to space.

IFS= 

There is one space after the IFS.

There are a lots way of doing that I particularly liked Charles way because it avoid a new process, but before know this I solved it with awk

pwd | awk -F/ '{print $NF}'

i usually use this in sh scripts

SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder

you can use this to automate things ...

Just remove any character until a / (or \, if you're on Windows). As the match is gonna be made greedy it will remove everything until the last /:

pwd | sed 's/.*\///g'

In your case the result is as expected:

λ a='/opt/local/bin'

λ echo $a | sed 's/.*\///g'
bin
Related