Unix ls命令选项打印文件作者

时间:2017-12-04 01:26:54

标签: unix options ls author

有谁能告诉我用哪个ls选项来打印文件的作者或所有者?我搜索了超过2个小时,我发现的唯一的事情是连字符连字符作者不起作用。我试过Unix.com,unixtutorial.com,Ubuntu.com和其他十几个网站。我使用了Google,Yahoo,Bing,DuckDuckGo。我准备放弃一切并放弃。

2 个答案:

答案 0 :(得分:0)

要获取作者,请将--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。

答案 1 :(得分:0)

我正在尝试所有这些,但没有人可以使用上面的代码。我想可能是因为我使用的是 ubuntu。对于 linux 系统,一个简单的 ls 命令,-author 然后 -l 就可以了。写下 author 会很累full 并且不要使用 -a,linux 可能会将其翻译为不同的命令。 ls -author -l | Filename 这将打印作者姓名和版本。print author name

相关问题