在了解如何存储密码之前,您需要弄清楚如何正确读取文件中的值。在 bash 中,用于确定 shell 如何将一行分成单个标记的主要工具是 Internal Field Separator(默认值:space tab newline)。该过程称为分词IFS 变量允许您设置将控制分词的字符。
您可以通过在IFS 中包含comma 来利用它来阅读诸如您的行之类的行。这将允许您指定单个变量以读取每个 name、initial、last、user name 和 password。 while 循环是完成此操作的常规方法 - 它允许您为该代码块设置 IFS 而不会影响脚本的其余部分。
你的例子是:
#!/bin/bash
[ -z "$1" ] && { ## validate one argument given on command line
printf "error: insufficient input. usage: %s filename.\n" "${0##*/}"
exit 1
}
[ -r "$1" ] || { ## validate it is a readable filename
printf "error: file not found/readable '%s'.\n" "$1"
exit 1
}
## read each line in file separated by ','
# set Internal Field Separator to break on ',' and '\n'
# protect against lack of '\n' on last line with $pw test
while IFS=$',\n' read -r first mi last uname pw || [ -n "$pw" ]; do
printf "name: %-5s %s. %-6s user: %s pass: %s\n" \
"$first" "$mi" "$last" "$uname" "$pw"
## Create User Accounts/Store Password Here...
done <"$1"
exit 0
输入
$ cat dat/useracct.txt
John,N,Snow,seords,cuai2Ohzdh
Jill,O,Rain,reords,cuai3Ohzdh
Jane,P,Sleet,peords,cuai4Ohzdh
输出
$ bash readuserfile.sh dat/useracct.txt
name: John N. Snow user: seords pass: cuai2Ohzdh
name: Jill O. Rain user: reords pass: cuai3Ohzdh
name: Jane P. Sleet user: peords pass: cuai4Ohzdh
然后,您可以使用所需选项创建用户帐户,并以您喜欢的任何方式存储密码。如果您有任何问题,请告诉我。