Get the file or directory owner in Bash for use in scripts on Linux

Profile image of Mattias Geniar

Mattias Geniar, January 12, 2016

Follow me on Twitter as @mattiasgeniar

If you ever need to retrieve the user that owns the file, or the group, you can use the very simple stat command. But instead of the usual grep/sed/awk dance, you can just set some additional parameters that retrieve only the user or group.

Here’s how that works:

#!/bin/bash
USER=$(stat -c '%U' /path/to/your/file)

From now on, the $USER variable holds the username of the owner of that file. Want the group? Just as easy:

GROUP=$(stat -c '%G' /path/to/your/file)

The stat commands allows for several output formats, for handling users/groups these are the most important:

%u     user ID of owner
%U     user name of owner
%g     group ID of owner
%G     group name of owner

Handy little tool!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.