readlink和realpath命令

Endless_daydream Lv4

linux命令readlink和realpath都是解析软链接,获得绝对路径的命令。

realpath会递归地解析直到不是软链接。

readlink默认只解析一层,使用-f选项则递归地解析,与realpath相同。

realpath --help:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
用法:realpath [选项]... 文件...
打印经过解析的绝对路径文件名;
除最后一部分外,文件名的所有组成部分必须存在

-e, --canonicalize-existing all components of the path must exist
-m, --canonicalize-missing no path components need exist or be a directory
-L, --logical resolve '..' components before symlinks
-P, --physical resolve symlinks as encountered (default)
-q, --quiet suppress most error messages
--relative-to=DIR print the resolved path relative to DIR
--relative-base=DIR print absolute paths unless paths below DIR
-s, --strip, --no-symlinks don't expand symlinks
-z, --zero end each output line with NUL, not newline

--help 显示此帮助信息并退出
--version 显示版本信息并退出

readlink --help:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
用法:readlink [选项]... 文件...
输出符号链接值或规范文件名。

-f, --canonicalize 递归的跟随给定文件名的所有符号链接以规范化,
除最后一个外所有组件必须存在
-e, --canonicalize-existing 递归跟随给定文件名的所有符号链接以规范化,
所有组件都必须存在
-m, --canonicalize-missing 通过递归地跟随指定文件名的各个组成部分的
符号链接来规范化文件名,
但不对各个组成部分的存在性作出要求
-n, --no-newline 不输出末尾的换行符
-q, --quiet
-s, --silent 不输出大多数的错误消息(默认启用)
-v, --verbose 报告错误消息
-z, --zero 以 NUL 字符而非换行符结束每个输出行
--help 显示此帮助信息并退出
--version 显示版本信息并退出

可以看出两者选项相近,功能基本重合。

对于除最后一个外所有组件必须存在的解释:

这句话的意思是指向的文件可以不存在,但其上级目录必须存在。用一个例子说明:

假设有目录如下:

1
2
3
4
/home/user/
├── existing_directory/
│ └── existing_file.txt
└── non_existing_directory/

realpath existing_directory/existing_file.txt,命令会成功并输出 /home/user/existing_directory/existing_file.txt,因为路径中的所有部分都存在。
realpath non_existing_directory/new_file.txt,命令会失败并报错,因为 non_existing_directory 这个目录不存在。
realpath existing_directory/new_file.txt,命令会成功并输出 /home/user/existing_directory/new_file.txt ,尽管 new_file.txt 这个文件不存在,但 existing_directory 目录是存在的。 这就是’除最后一个外所有组件必须存在’的情况。

  • Title: readlink和realpath命令
  • Author: Endless_daydream
  • Created at : 2024-05-20 17:22:58
  • Updated at : 2024-05-20 17:27:36
  • Link: https://endless_daydream.gitee.io/2024/05/20/linux/readlink-and-realpath/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
readlink和realpath命令