wc -c は追加の文字数を提供します。

wc -c は追加の文字数を提供します。

そのため、システムにユーザーを追加するスクリプトを作成し、ユーザー名の長さを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]$ 

空白にしても、まだ1文字でカウントされます。

[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:

この問題を特定する方法は?

ベストアンサー1

空白にしても何とか文字[。 。 .]誰かが私がこれを見つけるのを助けることができますか?

printf代わりに試してみてくださいecho

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

を使用すると、echo改行wc文字が計算されます。

あるいは、パイプなしで純粋なBashを使用する方が良いかもしれませんwc

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

おすすめ記事