iam*_*est 4 shell grep scripting bash wc
因此,我制作了一个将用户添加到系统的脚本,并希望将用户名的长度强制为 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
Run Code Online (Sandbox Code Playgroud)
这是完整的脚本,但我认为问题只出现在这里:
read -p 'Enter one usernames: ' USERNAME
nrchar=$(echo ${USERNAME} | wc -c)
echo $nrchar
Run Code Online (Sandbox Code Playgroud)
所以这个问题是,每当我输入一个 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]$
Run Code Online (Sandbox Code Playgroud)
即使我把它留空,它仍然以某种方式计算一个字符:
[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:
Run Code Online (Sandbox Code Playgroud)
如何识别这个问题?
即使我把它留空,它仍然以某种方式计算一个字符 [. . .] 有人可以帮我找出这个问题吗?
尝试printf代替echo
$ echo "" | wc -m
1
$ printf "" | wc -m
0
Run Code Online (Sandbox Code Playgroud)
使用echo,wc将计算一个换行符。
或者,也许更好,使用没有管道的纯 Bash 来wc:
$ string=foobar
$ echo "${#string}"
6
Run Code Online (Sandbox Code Playgroud)