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.
2 Answers
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
-
Thanks a lot. I like jilliagre's function, but I wanted a command to do it without parsing the ouput of another command. Dec 20, 2012 at 20:53
-
Sweet, a new terminal command to play with! I never knew about the stat command, but I will now abuse it in every way I can think of. Dec 21, 2012 at 1:03
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 whichstat
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.
-
2Might work great until you have a username with perhaps a space in it...– userDec 20, 2012 at 20:33
-
1@MichaelKjörling On Fedora 17:
sudo adduser "foo bar"
outputsadduser: invalid user name 'foo bar'
but it works fine if you try "foobar" (without a space). Therefore, spaces are not valid in usernames. Dec 20, 2012 at 20:40 -
Where in the question does it even specify Linux? I see a
unix
tag as well...– userDec 20, 2012 at 21:04 -
@MichaelKjörling The title starts out "linux - shell script -...". And then of course, there is the linux tag. Dec 20, 2012 at 22:04
-
1@BenjiWiebe: Spaces are valid in usernames, regardless of what
adduser
says about them. In fact, they're commonly used on Linux systems joined to MS Active Directory domains. Dec 20, 2012 at 22:38
for my $file (@ARGV) {$uid = (stat $file)[4]; $name = (getpwuid $uid)[0]; print "$name\n"}
orprint map {"$_\n"} map {(getpwuid $_)[0]} map {(stat $_)[4]} @ARGV
(whichever looks nicer to you)stat
andbash
/sh
installed.stat
.