POSIX analog of coreutils “stat” command?

坚强是说给别人听的谎言 提交于 2019-12-14 03:58:42

问题


Coreutils stat have --format= switch which report different info about file (owner, size, etc) in easy form for readers.

POSIX ls utility provide most of this info, but its output is hard to parse. Compare with one-liner:

[ `stat -c '%U' $f` = $USER ] && echo "You own $f" || echo Error!

Are there stat utility analog in POSIX?


回答1:


The short answer is no, POSIX does not provide a simple way to get the same output as stat. However, you can usually get relevant bits using other tools. To get the owner specifically:

ls -ld /path/of/file/or/directory | awk '{print $3}'



回答2:


It is not possible :-(

Your options are:

  • Use ls and parse that with awk; the output of ls -l is in POSIX, so you can rely on that. This works okay for some fields (such as the owner in your example), and not so good for others (such as the mtime).

  • Detect the stat version and switch parameters; GNU stat has -c, BSD stat has -f, other versions perhaps something else. stat is not in POSIX at all, and I don't know how widespread it is beyond Linux, BSD, and OSX, though.

  • Use a Perl or Python one-liner; this is not even remotely POSIX of course, but making the assumption that at least one of these languages is present is a fairly reasonable one in 2015, and it is easily detectable at startup if they are indeed present. It's also not an option if performance is any concern.

    Example, I've used mtime in all these examples, as this is difficult to get with ls:

    #!/bin/sh
    
    file="/etc/passwd"
    
    perl -e "print((stat(\"$file\"))[9])"
    echo
    
    echo "$file" | perl -e '$i = <STDIN>; chomp($i); print((stat($i))[9])'
    echo
    
    python -c "import os; print(os.stat(\"$file\").st_mtime, end='')"
    echo
    
    echo "$file" | python -c "import os, sys; print(os.stat(sys.stdin.readline()[:-1]).st_mtime, end='')"
    echo
    

    I would recommend the Perl version; not because I like Perl, but because this Python example only work correctly with Python 3 (specifically, the end='' bit to prevent printing newlines. A version to work with both Python 2 & 3 gets rather long:

     python2 -c "from __future__ import print_function; import os; print(os.stat('/etc/passwd') .st_mtime, end='')"
    

    You could also expand this with other languages (Ruby, PHP, Tcl, etc.), but Perl & Python are the most widespread by far.

    Documentation for: Perl stat(), Perl lstat() Python os.stat() .



来源:https://stackoverflow.com/questions/27828585/posix-analog-of-coreutils-stat-command

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