Unix ls command option to print file author

寵の児 提交于 2020-08-12 03:59:06

问题


Can anyone tell me which ls option to use to print the author or owner of a file? I have searched for over 2 hours and the only thing I have found is hyphen hyphen author which doesn’t work. I tried Unix.com, unixtutorial.com, Ubuntu.com and about a dozen other sites. I used Google, Yahoo, Bing, DuckDuckGo. I’m about ready to chuck it all and give up.


回答1:


To get the author, you combine --author with -l (it doesn't work without it). Keep in mind that, in most UNIXes that support ls --author, author and owner are the same thing, I believe it's only in the GNU Hurd where they're different concepts. Further, not all UNIXes actually provide the --author option.

The current owner you can get by looking at the output of ls -l - it's usually the third argument on the line (though this can change depending on a few things). So, simplistically, you could use:

ls -al myFileName | awk '{print $3}'

Of course, parsing the output of ls is rarely a good idea. You would be better off using a C program to call stat() on the file, and get the st_uid field to get the current owner:

#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;
}

Compile that to owner, then call it with owner myFileName to get the owner of the given file. It will attempt to find the textual name of the owner but will revert to the numeric ID if it cannot find the textual name, or if you put the -n flag on the end of your invocation.



来源:https://stackoverflow.com/questions/47625260/unix-ls-command-option-to-print-file-author

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!