Reputation: 233
I have started writing a small piece of code to print all the list of users available in the linux box. But I want to pass one by one user into my command to display each user details together.
root@bt# getent passwd | grep /home/ | cut -d ':' -f 1
root
san
postgres
Now I want to pass one by user in to the below command to display each user details together.
root@bt# chage -l ${user1} ; chage -l ${user2} etcc.
should I need to user for loop or while loop here? can any one help me in suggesting how to write the same?
Upvotes: 3
Views: 3069
Reputation: 6271
I would use xargs
, which runs a command on each output item of the previous pipe:
getent passwd | grep /home/ | cut -d ':' -f 1 | sudo xargs -I % sh -c '{ echo "User: %"; chage -l %; echo;}'
sudo
is used to get information about all users, if you don't have access to this information then you can remove sudo
-I %
is used to specify that %
is a placeholder for the input item (in your case a user)sh -c '{ command1; command2; ...;}'
is the command executed by xargs
on every %
item; in turn, the command sh -c
allows multiple shell commands to be executed%
, then runs chage -l
on this user and finished with a final empty echo
to format the ouputUpvotes: 1
Reputation: 241768
You can use the while
loop:
getent passwd | grep /home/ | cut -d ':' -f 1 | \
while read user ; do
chage -l "$user"
done
or the for
loop:
for user in $(getent passwd | grep /home/ | cut -d ':' -f 1) ; do
chage -l "$user"
done
or xargs
:
getent passwd | grep /home/ | cut -d ':' -f 1 | \
xargs -n1 chage -l
Upvotes: 1