Bash script get one directory back

Viewed 2816

I can get my current working directory with

my_dir=$(pwd)
echo $my_dir
/files/work/test

How do I get /files/work I don't want to change directories. I just need to get the /files/work directory.

3 Answers

Try one of these (assuming you didn't manually change $PWD):

  1. echo "${PWD%/*}"
    
  2. dirname "$PWD"    
    
  3. (cd .. && pwd)
    
echo `dirname \`pwd\``

It ll result the parent directory of present working directory

You can ascend one directory above:

$ cd ..

or you can dirname to print the one directory above:

$ dirname "/files/work/test"
/files/work
Related