【问题标题】:Add users in shell script with txt file使用 txt 文件在 shell 脚本中添加用户
【发布时间】:2015-10-14 13:16:53
【问题描述】:

我想添加一些在此文件中的用户,例如:

a b
c d
e f

名字总是姓氏

#!/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

在循环之前它工作正常,但我不能添加换行符。 回显显示a c e 和第二个姓氏b d f。 我尝试在其中添加换行符,但它不起作用。

我可以用什么来做这个? 因为我猜因为换行问题我无法添加用户。

我还在 stackoverflow 上搜索了一种方法来检查用户是否已通过 /dev/null 存在,但我必须使用哪个变量?

【问题讨论】:

    标签: linux shell ubuntu scripting


    【解决方案1】:

    逐行处理文件更容易:

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

    【讨论】:

    • 先读后写。但那是线条对吗?
    • 还有一个问题我忘了问,我必须在哪里添加密码?
    • @gladius: read 逐行读取,但它可以将一行中的几个单词读取到多个变量中。
    【解决方案2】:

    我不明白您的代码是什么意思,但是如果您想逐行读取文件并获取不同字段的值,则可以使用以下代码sn-p:

    #!/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"
    

    注意:您不能以您希望使用 bash 脚本的方式添加用户;因为系统会提示您输入密码,必须使用tty 提供密码,您可以使用expect 对其进行编程;或使用系统调用。

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2021-03-25
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      相关资源
      最近更新 更多