linux - shell script - How to output the owner of a file

06
2014-04
  • BenjiWiebe

    Is there a command to output the owner of a file, and nothing else? I suppose I could use ls and run it through sed, but if there is a better way, I would definitely use it.
    Thanks in advance.

  • Answers
  • sputnick
    stat -c %U file.txt
    

    ls is a tool for interactively looking at file information. Its output is formatted for humans and will cause bugs in scripts. Use globs or find instead. Understand why: http://mywiki.wooledge.org/ParsingLs

  • jlliagre

    I would use that function:

    lso() { ls -dl ${1:?usage: lso file} | awk '{print $3;exit}'; }
    

    Edit:

    • I thought about stat but I try to avoid using anything non standard when possible. I sticked with something portable (i.e. POSIX) as your question is tagged linux and unix, not just linux with which stat is quite standard..

    • As this question triggered a discussion about valid usernames, these are also defined by a Unix standard to be a string composed exclusively of characters from this list:

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

    a b c d e f g h i j k l m n o p q r s t u v w x y z

    0 1 2 3 4 5 6 7 8 9 . _ -

    with the additional restriction for the hyphen not to be the first character.

    I assumed no space was allowed. Just like anything else which is non-portable this can lead to unexpected results not only with my small function but with many Unix/Linux CLI utilities.


  • Related Question

    unix - How can I take the output of a shell script and place it in a file on the command line?
  • Questioner

    How can I take the output of a shell script and place it in a file on the command line?


  • Related Answers
  • Am.
    # write to file
    sh myscript > out.txt
    # append to file
    sh myscript >> out.txt
    # write both output and stderr to file
    sh myscript 2&1>> out.txt
    
  • Oren Mazor
    $ ./foo >> myoutputfile.txt