How to remove end folder name from a path in Linux

2020-05-06 21:04发布

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.

So for a path: /home/usr/Downloads/images I want to get /home/usr/Downloads.

标签: linux shell
1条回答
虎瘦雄心在
2楼-- · 2020-05-06 21:33

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)

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 ..'

Or

cdp() {
  cd ..
}
查看更多
登录 后发表回答