Add users in shell script with txt file

2019-09-13 18:35发布

问题:

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.