Subbing Duplicate username with a number at the end

1 command-line bash

Hello currently working on a school project for my unix class.

Creating a user menu to add/create username using the first name + last name to create username(first initial+first four of last)

Ex. John Smith = JSMIT

now I can add usernames, but if someone was to enter the same or similar user name, I need to be able to substitute it with a number at the end.

Ex. James Smith = JSMIT1

so far this is what I have, I know I need to use the substr function in awk, but im not sure how exactly.

I appreciate any help, thank you.

     looptest=y
while [ "$looptest" = y ]
do
        echo -n "Enter Name: "; read name
        echo -n "Enter Last Name "; read last
        echo -n "Continue(y)es or (n)o "; read looptest
        user="${name:0:1}""${last:0:4}"
        echo "$name:$last:$user" >> userData
        done
Run Code Online (Sandbox Code Playgroud)

Ser*_*nyy 5

One possible approach with grep

From your code, I see that you're appending to userData file, which means filenames would increase in their numerical suffix. So to get next available suffix, we could look through the userData file with grep and merely count number of lines where username occurs:

$ grep -c 'jsmit' users.txt                                                   
2
Run Code Online (Sandbox Code Playgroud)

Of course, if returned number is 0, we can just ignore that because it's a new username. Here's a just small script of how that'd work:

$ grep -c 'jsmit' users.txt                                                   
2
Run Code Online (Sandbox Code Playgroud)

Test with jsmit and jsmit1 already in the file:

$ ./indexed_usernames.sh                                                      
Enter first name: john
Enter lastname: smith 
jsmit2
Run Code Online (Sandbox Code Playgroud)

However , note that this is a very naive and simplistic way, and assumes no usernames are deleted or missing indexes and are added in linear fashion.

Other things to consider

  • As I understand you're building a small user database in shell script. Consider such case: what if we had jsmit,jsmit1, and jsmit2, but then we removed jsmit1. That means the script has to consider which numerical indexes are actually available, otherwise if we blindly increment numbers, that can result in a collision.

  • 考虑大写与小写用户名。如果我进入John Smithjohn smith是否会导致碰撞?您是否应该先将所有用户名转换为小写,然后再处理冲突?