2

I am a beginner at scripting but I created a text file called text.dat which contains only usernames in the file location /home/daniel/text.dat and I’m trying to run a script(called addusers.sh) that displays the names from that text file and will create a new user account on the system for each new user account specified in the text.dat file. For each user account that is created, append a line entry to the /home/daniel/logs/useraccounts.log file.  The line entry will contain the following information:  added | <user account name> | <day and time of creation>.

This is what I have so far:

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

1 Answer 1

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

Several things to note here:

  • Created users can't log in until a password has been set for each of them.
  • The printf will have to be altered to suit your own style.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .