Linux 脚本从文本文件中提取用户名

Linux 脚本从文本文件中提取用户名

我是脚本编写的新手,但我创建了一个名为 text.dat 的文本文件,该文件仅包含文件位置 /home/daniel/text.dat 中的用户名,我正在尝试运行一个脚本(名为 addusers.sh),该脚本显示该文本文件中的名称,并将在系统上为 text.dat 文件中指定的每个新用户帐户创建一个新用户帐户。对于创建的每个用户帐户,将一行条目附加到 /home/daniel/logs/useraccounts.log 文件。行条目将包含以下信息:   added | <user account name> | <day and time of creation>

这是我目前所拥有的:

#!/bin/bash
echo “cat text.dat”
newuser= grep /home/daniel/text.dat
sudo adduser $newuser

答案1

#!/bin/bash
LANG=C
myuser="/home/george/text.dat"

# create logs directory
mkdir -p ~/logs

# create log file
touch ~/logs/useraccounts.log

# make sure admin is running the script
[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"


# check if log file is empty, if not don't add a new header
file="~/logs/useraccounts.log"

# Add header in logs file if one isn't already there.
if [[ -s $file ]]
then
    # log file header

    printf "%s %12s %s %18s %s %32s %s\n" "|" "Added" "|" "User Account Name" "|" "Day and Time of Creation" "|" >> ~/logs/useraccounts.log

    printf "%50s\n" "========================================================================" >> ~/logs/useraccounts.log

fi


# remove any whitespaces and blank lines from file input
# before passing it to 'while command'
sed '/^[ \t]*$/d' $myuser | while read -r line
do
        name="$line"

        adduser --disabled-login --gecos "" $name


        # check if user was successfully added
        isthere=$(cut -d: -f1 /etc/passwd | grep "$name")


        # if user was added then make insert record into log file
        if [[ "$isthere" == "$name" ]]
        then

                 printf "%s %10s   %s %17s  %s %33s %s\n"  "|" "Yes" "|" "$name"  "|" "$(date)" "|"  >> ~/logs/useraccounts.log 

        else

                 printf "%s %10s   %s %17s  %s %33s %s\n"  "|" "No" "|" "$name"  "|" "$(date)" "|"  >> ~/logs/useraccounts.log



        fi   




done

这里有几点需要注意:

  • 创建的用户不能登录直到为每一个都设置了密码。
  • 必须printf进行修改才能适合你自己的风格。

相关内容