Bash

wc -c 給了我一個額外的字元數

  • September 7, 2018

所以我做了一個向系統添加使用者的腳本,我想強制使用者名的長度為 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 -m
1
$ printf "" | wc -m
0

使用echo,wc將計算換行符。

或者,也許更好的是,使用沒有管道的純 Bash 到wc

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

我也更喜歡 shell 的“參數擴展”方法;但如果你使用wc,你也可以使用它的字數統計選項:

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

您可能需要確保只使用 ASCII 字元 - 沒有多字節國際字元。

如果你走bash內部路徑,檢查空格可能是

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

引用自:https://unix.stackexchange.com/questions/463654