MangO_O
MangO_O

Reputation: 423

Retrieving only name of user who owns folder

I'm making a bash script that has to create subfolders and expand files into a mounted folder. My Problem is that I can't create subfolders as ROOT, i need to the commands in my script as:

su - UnknownUser -c "mkdir MAKEDir"

So my question is, how can I only retrieve the user name when doing commands like

ls -l

Thanks for any input!

Upvotes: 0

Views: 202

Answers (4)

Jack
Jack

Reputation: 6158

If "parent" is the parent directory...

user=$(ls -ld ${parent} | awk '{print $3}')
sudo -u $user mkdir ${parent}/child1
sudo -u $user mkdir ${parent}/child2
sudo -u $user mkdir ${parent}/child1/grandchild1
sudo -u $user mkdir ${parent}/child1/grandchild2

Upvotes: 0

chepner
chepner

Reputation: 530920

The stat command varies greatly by implementation, but the following will work

# GNU stat
# -c may be used in place of --format
$ stat --format %U file.ext

# BSD (Mac OS X, anyway) stat
$ stat -f %Su file.ext

Upvotes: 4

Cwissy
Cwissy

Reputation: 2156

Use stat -c with a format of %U for the textual name of the owner, or %u for the uid of the owner (or %G/%g for group)

stat -c %U <filename>

Upvotes: 4

gregory
gregory

Reputation: 12885

use awk:

for the user of file foo: ls -l foo | awk '{print $3}'

or, for user and filename together: ls -l | awk '{print $3, $9 }'

Upvotes: 0

Related Questions