4

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?

1
9

Even if I leave it blank, it still somehow counts one character [. . .] Could somebody please help me identify this problem?

Try printf instead of echo

$ echo "" | wc -m
1
$ printf "" | wc -m
0

Using echo, wc will count a newline character.

Or, perhaps better, use pure Bash without piping to wc:

$ string=foobar
$ echo "${#string}"
6
0
0

I would prefer the shell's "parameter expansion" method as well; but if you use wc, you could use its word count option as well:

read LENGTH WORDS REST <<<$(echo -n ${USERNAME} | wc -cw)
echo $LENGTH $WORDS 
2 8

You may want to make sure only ASCII characters are used - no multibyte international characters.

Should you go the bash internals path, the check for spaces could be

[ "$USERNAME" = "${USERNAME%% *}" ] && echo No spaces || echo some spaces

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.