如何从Linux脚本中的路径中删除结束文件夹名称? [英] How to remove end folder name from a path in Linux script?

查看:97
本文介绍了如何从Linux脚本中的路径中删除结束文件夹名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Linux中创建一个简单的命令,类似于DOS中的cd...我试图做的是制作一个脚本,该脚本通过删除最后一个文件夹名称来将目录更改为必须从pwd获取的路径.

I am trying to make a simple command in Linux similar to cd.. in DOS. What I tried is to make a script that changes directory to a path, which I have to get from pwd, by removing the last folder name.

对于路径:/home/usr/Downloads/images我想获取/home/usr/Downloads.

推荐答案

您可以使用dirname命令来执行所需的操作,它会删除文件中的最后一个部分".如果您提供的是目录,则将获得父目录.

You can use the dirname command to do what you're asking for, it remove the last "part" from a file. If what you give it is a directory, you'll get the parent directory.

parent=$(dirname /your/path/here)

但是用脚本执行cd..是不可能的-cd仅会影响运行脚本的外壳,而不会影响调用脚本的外壳.

But doing a cd.. with a script is not possible - the cd would only affect the shell that the script is running in, not the shell that invoked the script.

因此,您必须使用别名或函数.

So you have to use an alias or a function.

alias cd..='cd ..'

cdp() {
  cd ..
}

这篇关于如何从Linux脚本中的路径中删除结束文件夹名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆