gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:01:15 24 4
gpt4 key购买 nike

我有一个简单的脚本来演示这个名为 getpath.sh 的问题:

#!/bin/bash
# getpath.sh

path="$1"
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="$1"

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 :

关于bash - 在bash脚本中使用升级符号..、../..、.. n-level up时如何获取升级目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61811992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com