If I have a file path such as...
/home/smith/Desktop/Test
/home/smith/Desktop/Test/
How do I change the string so it will be the parent dir
if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd)
. This would give 3 parents directories up
...but what is "seen here" is broken. Here's the fix:
> pwd
/home/me
> x='Om Namah Shivaya'
> mkdir "$x" && cd "$x"
/home/me/Om Namah Shivaya
> parentdir="$(dirname "$(pwd)")"
> echo $parentdir
/home/me
This would go up to the parent folder
cd ../
use this : export MYVAR="$(dirname "$(dirname "$(dirname "$(dirname $PWD)")")")"
if you want 4th parent directory
export MYVAR="$(dirname "$(dirname "$(dirname $PWD)")")"
if you want 3rd parent directory
export MYVAR="$(dirname "$(dirname $PWD)")"
if you want 2nd parent directory
dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"
Works if there is a trailing slash, too.
Just use echo $(cd ../ && pwd)
while working in the directory whose parent dir you want to find out. This chain also has the added benefit of not having trailing slashes.