Find the owner of a directory or file, but only return that and nothing else
stat
from GNU coreutils can do this:
stat -c '%U' /path/of/file/or/directory
Unfortunately, there are a number of versions of stat
, and there's not a lot of consistency in their syntax. For example, on FreeBSD, it would be
stat -f '%Su' /path/of/file/or/directory
If portability is a concern, you're probably better off using Gilles's suggestion of combining ls
and awk
. It has to start two processes instead of one, but it has the advantage of using only POSIX-standard functionality:
ls -ld /path/of/file/or/directory | awk '{print $3}'
Parsing the output of ls
is rarely a good idea, but obtaining the first few fields is an exception, it actually works on all “traditional” unices (it doesn't work on platforms such as some Windows implementations that allow spaces in user names).
ls -ld /path/to/directory | awk 'NR==1 {print $3}'
Another option is to use a stat
command, but the problem with stat
from the shell is that there are multiple commands with different syntax, so stat
in a shell script is unportable (even across Linux installations).
Note that testing whether a given user is the owner is a different proposition.
if [ -n "$(find . -user "$username" -print -prune -o -prune)" ]; then
echo "The current directory is owned by $username."
fi
if [ -n "$(find . -user "$(id -u)" -print -prune -o -prune)" ]; then
echo "The current directory is owned by the current user."
fi
One can also do this with GNU find:
find $directoryname -maxdepth 0 -printf '%u\n'
This isn't portable outside of the GNU system, but I'd be surprised to find a Linux distribution where it doesn't work.