用于添加用户的bash脚本

时间:2017-10-13 00:10:25

标签: bash cut

我创建了一个bash脚本,用于从文本文件中读取用户名,组等信息,并在linux中基于它创建用户。代码似乎正常运行并根据需要创建用户。但是文本文件最后一行中的用户信息总是被误解。即使我删除它,然后下一个最后一行被误解,即文本被错误地读取。 `

#!/bin/bash
userfile="users.txt"
IFS=$'\n'
if [ ! -f "$userfile" ]
then
  echo "File does not exist. Specify a valid file and try again. "
  exit
fi
groups=(`cut -f 4 "$userfile" | sed 's/ //'`)
fullnames=(`cut -f 1 "$userfile" | sed 's/,//' | sed 's/"//g'`)
username1=(`cut -f 1 "$userfile" |sed 's/,//' | sed 's/"//' | tr [A-Z] [a-z] | awk '{print substr($2,1,1) substr($3,1,1) substr($1,1,1)}'`)
username2=(`cut -f 4 "$userfile" | tr [A-Z] [a-z] | awk '{print substr($1,1,1)}'`)
i=0
n=${#username1[@]}
for (( q=0; q<n; q++ ))
do
usernames[$q]=${username1[$q]}"${username2[$q]}"
done
declare -a usernames
x=0
created=0
for user in ${usernames[*]}
do
adduser -c ${fullnames[$x]} -p 123456789 -f 15 -m -d /home/${groups[$x]}/$user -K LOGIN_RETRIES=3 -K PASS_MAX_DAYS=30 -K PASS_WARN_AGE=3 -N -s /bin/bash $user 2> /dev/null
usermod -g ${groups[$x]} $user
chage -d 0 $user
  let created=$created+1
x=$x+1
echo -e "User $user created    " 
done
echo "$created Users created"

enter image description here`

1 个答案:

答案 0 :(得分:0)

#!/bin/bash

userfile="./users.txt"; #  <-- Config

while read line; do

    # FULL NAME
        # Capture all between quotes as full name
        fullname=$(printf '%s' "${line}" | sed 's/^"\(.*\)".*/\1/')

        # Remove spaces and punctuations???:
        fullname=$(printf '%s' "${fullname}" | tr -d '[:punct:][:blank:]')

    # Right-side names:
        partb=$(printf '%s' "${line}" | sed "s/^\".*\"//g")

        # CODE 1, capture second row
        code1=$(printf '%s' "${partb}" | cut -f 2 )

        # CODE 2, capture third row
        code2=$(printf '%s' "${partb}" | cut -f 3 )

        # GROUP, capture fourth row
        group=$(printf '%s' "${partb}" | cut -f 4 )

    # Print only for report
    echo "fullname: ${fullname}\n code 1: ${code1}\n code 2: ${code2}\n group: ${group}\n"

done <${userfile}

也许这些是您想要的字段,现在您可以在变量中操作它们:$ fullname,$ code1,$ code2和$ group。

虽然您观察到的失败可能是由于文本文件中的某个错误的引号或换行符,但在附加的屏幕截图中我可以看到一个错过的引号。