Reputation: 369
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/
Upvotes: 3
Views: 3056
Reputation: 46826
Rather than doing any string manipulation or launching commands in a subshell, you can refer to the parent directory of any directory as ..
locally or if you can trust the $PWD
variable, you can use $PWD/..
.
Of course, this just lets you USE the parent directory, it doesn't give you the NAME of the parent directory. For that, you already have a couple of usable alternatives. For one more, read on.
In bash, the cd
builtin command has two options, -P
which tells cd
to use the physical directory structure traversing the directory structure as it resolves symbolic links, and -L
about which the man page says this:
the -L option forces symbolic links
to be followed by resolving the link after processing instances
of .. in dir. If .. appears in dir, it is processed by removing
the immediately previous pathname component from dir, back to a
slash or the beginning of dir.
So ... while you might be perfectly fine with the following:
parentdir="$(cd ..; pwd)"
You can therefore get the parent directory with:
parentdir="$(cd -L ..; pwd)"
Note that while this does involve a directory change, the change is effectively within a subshell ($(...)
), so it doesn't affect your script.
Note that I say "effectively" because strictly speaking, $(...)
, cd
and pwd
are all built-in to bash, so you're not actually spawning new shells.
Upvotes: 2
Reputation: 784958
You can use BASH string manipulation to get parent's parent directory path of any full path:
$> pwd
/dir1/dir2/dir3/dir4
$> echo "${PWD%/[^/]*}"
/dir1/dir2/dir3
%/[^/]*
removes last matching pattern /*
from $PWD
which is the current working directory.
Upvotes: 2
Reputation: 18351
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
Upvotes: 3