Skip to main content
edited tags; edited tags
Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 264
Source Link

How to dynamically change owner of directory using awk output?

What I want to do :

  • Takes user & their home directory list from /etc/passwd
  • use the username and home address as parameters and change ownership of those directory to that user.

Current outputs:

trimmed output of: cat /etc/passwd

##
# User Database
# 
# Note that this file is consulted directly only when the system is running
# in single-user mode.  At other times this information is provided by
# Open Directory.
#
# See the opendirectoryd(8) man page for additional information about
# Open Directory.
##
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
_taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false
_networkd:*:24:24:Network Services:/var/networkd:/usr/bin/false

trimmed output of: cat /etc/passwd | grep "^[#;]" -v

nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
_taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false
_networkd:*:24:24:Network Services:/var/networkd:/usr/bin/false
_installassistant:*:25:25:Install Assistant:/var/empty:/usr/bin/false

Now I had to remove the starting '_' so I used follwing command:

trimmed output of: cat /etc/passwd | grep "^[#;]" -v | sed s/"_"//

nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false
networkd:*:24:24:Network Services:/var/networkd:/usr/bin/false

Finally I took out the username and directory using awk command:

cat /etc/passwd | grep "^[#;]" -v | sed s/"_"// | awk -F\: '{print $1" "$6}' (output trimmed)

nobody /var/empty
root /var/root
daemon /var/root
uucp /var/spool/uucp
taskgated /var/empty
networkd /var/networkd
installassistant /var/empty
lp /var/spool/cups
postfix /var/spool/postfix
scsd /var/empty
ces /var/empty
appstore /var/db/appstore

Here's what I want to do further!

Take the FIRST argument and assign the ownership of SECOND argument to it. How should I proceed?