所以我做了一个向系统添加用户的脚本,我想强制用户名的长度为 8 个字符或以下。
#!/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
这是完整的脚本,但我认为问题只出在某个地方:
read -p 'Enter one usernames: ' USERNAME
nrchar=$(echo ${USERNAME} | wc -c)
echo $nrchar
所以问题是,每当我输入一个 8 个字符的用户名时,nrchar 变量似乎总是会再添加一个字符,如下所示:
[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]$
即使我将其留空,它仍然以某种方式计算一个字符:
[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:
如何识别这个问题?
尝试
printf
代替echo
使用
echo
,wc
将计算换行符。或者,也许更好的是,使用没有管道的纯 Bash 到
wc
:我也更喜欢 shell 的“参数扩展”方法;但如果你使用
wc
,你也可以使用它的字数统计选项:您可能需要确保只使用 ASCII 字符 - 没有多字节国际字符。
如果你走
bash
内部路径,检查空格可能是