I'm working on an industrial application for the Pi, and for that we need to, of course, change the username. I don't want to do this manually everytime, so I want to use a script. So far I have written a script for writing the image to the SD card and an install script that installs all the right dependencies, repositories etc. Now I have had good results changing the username manually based on the answer of Mike Lutz in this question, which states
exec sudo -s cd / usermod -l newname -d /home/newname -m oldname
unfortunately, this does not work if you want to use it in a script, because the script will still be running on your old username, and therefor the username can't be changed.
So what I have resorted to now, is in the imaging to SD card script, I have written the following:
NEWNAME=pareto boot_path=/media/pareto/pi_boot filesystem_path=/media/pareto/pi_filesystem #check for mounted sd card => unmount echo "Unmounting SD card" sudo umount /dev/mmcblk0p1 sudo umount /dev/mmcblk0p2 # mount SD card partitions to the right folders echo "Mounting SD card partitions" sudo mount -t vfat /dev/mmcblk0p1 $boot_path sudo mount -t ext4 /dev/mmcblk0p2 $filesystem_path # replace username 'pi' with '$NEWNAME' echo "Replacing all instances of user 'pi' with '$NEWNAME'" for i in passwd shadow group gshadow sudoers; do sudo sed -i "s/:pi/:$NEWNAME/g" $filesystem_path/etc/$i sudo sed -i "s/^pi:/$NEWNAME:/g" $filesystem_path/etc/$i sudo sed -i "s/\/pi:/\/$NEWNAME:/g" $filesystem_path/etc/$i done # change the home folders name to correspond with $NEWNAME sudo mv $filesystem_path/home/pi $filesystem_path/home/$NEWNAME
So far it seems to work, but it feels very dirty. Is there a better way to change the username from a script (either via SSH/UART console) and if not, am I missing some important files I should change as well?