I have a file (users_uid) with users and uid are two parameters as given below :

    assds  611
    dsdsd  612
    xyzx   613
    rerer  614

These users exist in the machine. I want to change the uid of each user to that value given right for the username. I know that I can modify the uid using usermod -u <uid> <user>. But I don't know how to read the two values in the file and put them as the 2 parameters in a for loop with usermod command.


awk '{print "usermod -u "$2" "$1}' users_uid | bash

  • Thanks It worked ! But the sed is not required i think. # cat users_uid |awk '{print "usermod -u "$2" "$1}' | bash – nitins Dec 8 '11 at 13:03
  • 1
    Sed it required in case the first line is like in your example users uid. Otherwise it isn't required. – rush Dec 8 '11 at 13:06
  • @nitins: if the users_uid file doesn't contain column name (the first line), no need to use cat: awk '{ print "usermod -u "$2" "$1 }' users_uid | bash. – quanta Dec 8 '11 at 13:14
  • Yes you are correct. I actually don't have that line. Just added here to make it clear – nitins Dec 8 '11 at 13:15
  • I've removed that line to make it clear that the "header" is not actually in the file. – Monty Harder Jul 15 '13 at 14:51

The accepted answer runs the risk of executing malicious or accidental content in the data file. Here is the correct way to do what you want without spawning awk and an additional copy of bash plus it's safe from the risk I mentioned.

while read -r user uid
    usermod -u "$user" "$uid"
done < users_uid

As a one-liner:

while read -r user uid; do usermod -u "$user" "$uid"; done < users_uid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.