The both commands in the while loop need to be run as root, so either add sudo
s or save this as a bash script and run that with sudo
(probably preferable).
awk -F ':| ' '{print $1, $2, $3}' users.txt |
while read user password homedir; do
adduser --home "$homedir" "$user"
echo "$password" | passwd "$user" --stdin
done
Alternatively, as you've pointed out, you can do more inside awk
. We can have it print the entire command:
$ awk -F ':| ' '{ print("adduser --home", $3, $1"; echo", $2 " | passwd", $1) }' users.txt
adduser --home /home/almacen1 Jperez; echo 1234 | passwd Jperez
adduser --home /home/contabilidad1 Lgomez; echo 1234 | passwd Lgomez
adduser --home /home/almacen2 Pfernandez; echo 1234 | passwd Pfernandez
adduser --home /home/direccion1 Mramos; echo 1234 | passwd Mramos
And then just have it pipe all that into a shell (while running):
$ awk -F ':| ' '{ print("adduser --home", $3, $1"; echo", $2 " | passwd", $1) | "/bin/bash" }' users.txt
adduser: Only root may add a user or group to the system.
passwd: user 'Jperez' does not exist
adduser: Only root may add a user or group to the system.
passwd: user 'Lgomez' does not exist
adduser: Only root may add a user or group to the system.
passwd: user 'Pfernandez' does not exist
adduser: Only root may add a user or group to the system.
passwd: user 'Mramos' does not exist
Obviously you would need to run the above with sudo
(or as root) in order for it to run (that's why it's vomiting errors). You could use awk
's system()
command but then you have to spend more time concatenating the strings. print()
makes this really simple so I went with that.
Just for clarification, by that I mean to run sudo awk -F ':| ' '{ print("adduser --home", $3, $1"; echo", $2 " | passwd", $1) | "/bin/bash" }' users.txt