【发布时间】:2017-12-04 01:26:54
【问题描述】:
谁能告诉我使用哪个 ls 选项来打印文件的作者或所有者?我已经搜索了 2 个多小时,我唯一发现的是连字符连字符作者不起作用。我尝试了 Unix.com、unixtutorial.com、Ubuntu.com 和其他十几个站点。我使用谷歌、雅虎、必应、DuckDuckGo。我已经准备好放弃一切并放弃了。
【问题讨论】:
谁能告诉我使用哪个 ls 选项来打印文件的作者或所有者?我已经搜索了 2 个多小时,我唯一发现的是连字符连字符作者不起作用。我尝试了 Unix.com、unixtutorial.com、Ubuntu.com 和其他十几个站点。我使用谷歌、雅虎、必应、DuckDuckGo。我已经准备好放弃一切并放弃了。
【问题讨论】:
要获得作者,您将--author 与 -l 结合使用(没有它就无法工作)。请记住,在大多数支持ls --author 的 UNIX 中,作者和所有者是相同的,我相信只有在 GNU Hurd 中它们是不同的概念。此外,并非所有 UNIX 实际上提供--author 选项。
您可以通过查看ls -l 的输出来获得当前的所有者 - 它通常是该行的第三个参数(尽管这可能会根据一些事情而改变)。因此,简单地说,您可以使用:
ls -al myFileName | awk '{print $3}'
当然,解析ls 的输出很少是个好主意。您最好使用 C 程序在文件上调用 stat(),并获取 st_uid 字段以获取当前所有者:
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int Usage(char *errStr) {
fprintf(stderr, "*** ERROR: %s\n", errStr);
fprintf(stderr, "Usage: owner <file> [-n]\n");
fprintf(stderr, " '-n' forces numeric ID\n");
return 1;
}
int main(int argc, char *argv[]) {
if ((argc != 2) && (argc != 3))
return Usage("Incorrect argument count");
if ((argc == 3) && (strcmp(argv[2], "-n") != 0))
return Usage("Final parameter must be '-n' if used");
struct stat fileStat;
int retStat = stat(argv[1], &fileStat);
if (retStat != 0)
return Usage(strerror(errno));
struct passwd *pw = getpwuid (fileStat.st_uid);
if ((argc == 3) || (pw == NULL)) {
printf("%d\n", fileStat.st_uid);
return 0;
}
puts(pw->pw_name);
return 0;
}
将其编译为owner,然后使用owner myFileName 调用它以获取给定文件的所有者。它将尝试查找所有者的文本名称,但如果找不到文本名称,或者如果您在调用结束时放置了 -n 标志,它将恢复为数字 ID。
【讨论】:
--author 在任何 BSD 中都不可用。我不知道它是不是只有 Linux。
ls 手册页清楚地表明您应该使用-l:--author with -l, print the author of each file
我正在尝试所有这些,但上面的代码都没有工作。我想可能是因为我使用的是 ubuntu。对于 linux 系统,一个简单的 ls 命令,-author 然后 -l 就可以了。厌倦了写作者full 并且不要使用 -a,linux 可能会将其翻译为不同的命令。
ls -author -l | Filename
这将打印作者姓名和版本。print author name
【讨论】: