Im looking for a way inside a bash script to return the owner of a file. I'm guessing that this is possible using "gawk" but I've honestly got no clue and there doesn't seem to be a comprehensible answer already posted online.


Use stat for that.

In a GNU system:

  • To get the username of the owner:

    stat -c '%U' file.txt
  • To get the user ID (UID) of the owner:

    stat -c '%u' file.txt

Assuming the file is file.txt.

For FreeBSD and Mac OS X (thanks to @cas):

  • For username:

    stat -f '%Su' file.txt
  • For UID:

    stat -f '%u' file.txt
| improve this answer | |
  • 1
    That's correct for GNU stat. For FreeBSD (and Mac OS X) stat, use stat -f '%u' file.txt for UID and stat -f '%Su' file.txt for user name. it's a real shame that GNU and *BSD stat haven't standardised on how to specify custom output formats. – cas Apr 6 '16 at 3:31
  • @cas Thanks.. i have added that to the answer.. – heemayl Apr 6 '16 at 3:34
  • @heemayl Thank you, that perfectly answered my question. I used stat -c '%U' . YNWA! – Abul Hussan Apr 6 '16 at 3:53
  • @AbulHussan Great !! YNWA :) – heemayl Apr 6 '16 at 3:54
ls -l foo

Field #3 is owner, #4 is group. So:

set -- $(ls -l foo) ; echo $3

But stat is better, when available.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.