Joster Joster - 2 months ago 6
Linux Question

Shell Script: Need to use previous folder than current directory

Having this structure:


/dir1/dir2/dir3/dir4/my_script.sh


At one point in my script a need to store the complete path to dir3 into a variable.
I know this works:

CURRENT=`pwd`


But, How can I store the previous one?

WARNING: I have searched for similar questions, but all include changing the current directory, which is something i want to avoid.

Edit: What I mean is, as i'm running my_script.sh, the current directory is /dir1/dir2/dir3/dir4/
I want to store in a variable just: /dir1/dir2/dir3/

PS. PS.
Answer

How about using dirname ?

dirname $(pwd)
/dir1/dir2/dir3

To store the value of one directory up in a variable :

 x=$(dirname $(pwd))
 echo $x
 /dir1/dir2/dir3
Comments