在bash中获取文件的父目录 [英] get parent directory of a file in bash

查看:124
本文介绍了在bash中获取文件的父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取文件的父目录?

How do I get a parent directory for a file?

我希望它在所有名称上都是安全的:

I want it to be safe on all kind of names:

.
..
path/to/my/file
/absolute/path/to/my/file
'-rf --no-preserve-root whatever'/test.zip
(symbolic links)
`'"`'{(})

与遍历文件名中指定的路径相比,我更感兴趣的是获取文件系统上的规范位置.

I am more interested getting the canonical location on the file system than in traversing the path stated in the filename.

请注意,有与此类似的问题,但它们都不关注正确性,相对/绝对路径和不安全"名称:

Note that there are similar questions to this one, but none of them focuses on correctness, relative/absolute paths and "unsafe" names:

[1] bash获取当前目录的父目录

[2] 获取脚本的父目录

[3] bash到文件父目录的文件路径

推荐答案

真正安全的解决方案:

parent_dir="$(dirname -- "$(realpath -- "$file_name")")"

如果您的系统没有realpath,但是确实有readlink,则应该可以:

If your system does not have realpath but does have readlink, this should work:

parent_dir="$(dirname -- "$(readlink -f -- "$file_name")")"

这篇关于在bash中获取文件的父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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