How to get level up directory when using level up symbol .. , ../.. , .. n-level up in bash script

Viewed 90

I have a simple script to demonstrate this question called getpath.sh:

#!/bin/bash
# getpath.sh

path="$1"
if [ -z "$path" ]; then
   "details of [$PWD] :" 
else
   echo "details of [$path] : "
fi

Let's say I'm running this script in this directory: /home/root/mypath1/mypath2

example when I run getpath.sh without argument:

./getpath.sh

output: details of /home/root/mypath1/mypath2

Then, when I run getpath.sh script with an argument:

./getpath.sh /etc/nginx

output: details of /etc/nginx 

The above results are ok but I want to get full path of the directory n-level up using '..'. Example when I run this script with '..' argument:

./getpath.sh ..

output: details of ..  
the expected output should be: details of /home/root/mypath1

Another one

./getpath.sh ../..

output: details of ..
the expected output should be: details of /home/root/

and the last example:

.getpath.sh ../../..

output: details of ..
the expected output should be: details of /home

What can I modify to make it work?

1 Answers

The easiest approach would be to cd "$path", if what the user passed in is a directory, and set the path to . if nothing is passed in.

#!/bin/bash
path="$1"

if [ -z "$path" ]; then
  path="."
fi

if [ -d "$path" ]; then
  cd "$path"
  path=$PWD
fi

echo "details of $path :"

Gives this output for me:

tmp$ ./getpath.sh
details of /mnt/c/Users/ianmc/tmp :
tmp$ ./getpath.sh ../..
details of /mnt/c/Users :
Related