[英]Add users in shell script with txt file
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 ace
and second for lastname bdf
. 回声显示ace
和秒,表示姓氏bdf
。 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? 我还搜索了stackoverflow,以找出一种方法来检查用户是否已经存在/dev/null
但是我必须使用哪个变量呢?
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
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; 注意:您无法以使用bash脚本的方式添加用户; since you will be prompted for password which must be supplied using tty
you can use expect
to program it; 因为将提示您输入必须使用tty
提供的密码,所以可以使用expect
进行编程; or use system calls. 或使用系统调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.