Add users in shell script with txt file

僤鯓⒐⒋嵵緔 提交于 2019-12-25 03:04:42

问题


I want to add some users who are in this file like:

a b
c d
e f

firstname lastname always

#!/bin/bash
Lines=$(cat newusers.txt | wc -l)


first=$(cat newusers.txt | awk '{print $1}')
last=$(cat newusers.txt | awk '{print $2}')

#test
echo $Lines;
echo $first;
echo $last;

until [ -z $1]; then

useradd - m -d /home/$1 -c "$1 + $2" $1

fi

before loop it works fine but I can't add newline. The echo shows a c e and second for lastname b d f. I tried to add newline in but it doesn't works.

What can i use for this? Because I guess I can't add the user because of the newline problem.

I also searched on stackoverflow to find out a way to check if the user already exists by /dev/null but which variable do i have to use for it?


回答1:


It's easier to process the file line by line:

while read first last ; do
    useradd -m -d /home/"$first" -c "$fist + $last" "$first"
done < newusers.txt



回答2:


I do not understand what you mean to do by your code, but if you want to read the file line by line and get the values of different fields then you can use the following code snippet:

#!/bin/bash
filename="newusers.txt"
while read -r line
do
    fn=$( echo "$line" |cut -d" " -f1 )
    ln=$( echo "$line" |cut -d" " -f2 )
    echo "$fn $ln"
done < "$filename"

Note: You cannot add users the way you want to using bash script; since you will be prompted for password which must be supplied using tty you can use expect to program it; or use system calls.



来源:https://stackoverflow.com/questions/33126405/add-users-in-shell-script-with-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!