So I made a script that adds users to the system, and I wanted to force the length of the usernames to 8 characters or below.
#!/bin/bash
# Only works if you're root
for ((a=1;a>0;a)); do
if [[ "$UID" -eq 0 ]]; then
echo "Quit this shit anytime by pressing CTRL + C"
read -p 'Enter one usernames: ' USERNAME
nrchar=$(echo ${USERNAME} | wc -c)
echo $nrchar
spcount=$(echo ${USERNAME} | tr -cd ' ' | wc -c)
echo $spcount
if [[ "${nrchar}" -ge 8 ]]; then
echo "You may not have more than 8 characters in the username"
elif [[ "${spcount}" -gt 0 ]]; then
echo "The username may NOT contain any spaces"
else
read -p 'Enter one names of user: ' COMMENT
read -s -p 'Enter one passwords of user: ' PASSWORD
useradd -c "${COMMENT}" -m ${USERNAME}
echo ${PASSWORD} | passwd --stdin ${USERNAME}
passwd -e ${USERNAME}
fi
echo "------------------------------------------------------"
else
echo "You're not root, so GTFO!"
a=0
fi
done
That's the full script, but I think the problem is only here somewhere:
read -p 'Enter one usernames: ' USERNAME
nrchar=$(echo ${USERNAME} | wc -c)
echo $nrchar
So the problem with this is, whenever I enter a 8 character username, the nrchar variable seems to always add one more character to it, as so:
[vagrant@localhost vagrant]$ sudo ./exercise2-stuffs.sh
Quit this shit anytime by pressing CTRL + C
Enter one usernames: userdoi1
9
0
You may not have more than 8 characters in the username
------------------------------------------------------
Quit this shit anytime by pressing CTRL + C
Enter one usernames: ^C
[vagrant@localhost vagrant]$
Even if I leave it blank, it still somehow counts one character:
[vagrant@localhost vagrant]$ sudo !.
sudo ./exercise2-stuffs.sh
Quit this shit anytime by pressing CTRL + C
Enter one usernames:
1
0
Enter one names of user:
How to identify this problem?