如何从Linux脚本中的路径中删除结束文件夹名称? [英] How to remove end folder name from a path in Linux script?
问题描述
我试图在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屋!