在 bash 脚本中使用升级符号 .. , ../.. , .. n-level up 时如何获得升级目录

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

我有一个简单的脚本来演示这个问题,叫做 getpath.sh:

#!/bin/bash
# getpath.sh

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

假设我运行在这个目录中安装这个脚本:/home/root/mypath1/mypath2

我 运行 getpath.sh 没有参数的例子:

./getpath.sh

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

然后,当我 运行 getpath.sh 带有参数的脚本时:

./getpath.sh /etc/nginx

output: details of /etc/nginx 

上面的结果没问题,但我想使用'..'获取n级目录的完整路径。 例如,当我 运行 这个带有 '..' 参数的脚本时:

./getpath.sh ..

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

另一个

./getpath.sh ../..

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

最后一个例子:

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

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

我可以修改什么使其工作?

最简单的方法是 cd "$path",如果用户传入的是一个目录,并将路径设置为 .如果没有传入任何内容。

#!/bin/bash
path=""

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

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

echo "details of $path :"

给我这个输出:

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