I have a username.txt which contains their username and specific group. As of right now i’m trying to create a bash script which allows me to create an account for each user and add the user to its group in one command.
this is currently my failed bash script(i know pretty much everything is wrong but i hope you guys got a clear idea on it):
#!/bin/bash sudo addgroup staff sudo addgroup visitors username="username.txt" while read line; do sudo useradd $-Eo '^[^,]+' $username; if [grep staff $username]; then sudo usermod -a -G staff else sudo usermod -a -G visitors done < $username
This is what is inside my username.txt file:
ellipsiscoterie,visitor magnetcommonest,visitor belateddefensive,staff bobstercaramelize,staff
Advertisement
Answer
Let’s go through your script.
#!/bin/bash sudo addgroup staff sudo addgroup visitors username="username.txt"
OK. There is some debate about using sudo
in scripts, but I’m not against it.
while read line; do
You read the line from STDIN, which is your input file. The variable line
contains ellipsiscoterie,visitor
in the first iteration.
sudo useradd $-Eo '^[^,]+' $username;
$-
prints The current set of options in your current shell. It will produce something like himBH
. The next argument seems a regular expression, and the last argument is the filename that you use. So the command here is:
sudo useradd himBHEo '^[^,]+' username.txt
Hint: if you are unsure of the arguments, check with an echo (echo $-Eo '^[^,]+' $username
) before you add them to a sudo-ed command.
This is not what you want. First, you probably want to use the variable line
instead of username
. Why would you otherwise loop through that file?
Second, read-up on variable expansion in bash
. For now, try:
line=ellipsiscoterie,visitor echo ${line%,*} echo ${line#*,}
So the line would probably need to be:
sudo useradd ${line%,*}
if [grep staff $username]; then
This is wrong in almost everything.
- the
[
and]
require spaces to set them apart - but you dont want to do a
test
, you want to see if the grep succeeds, so the[
and]
are not needed anyway - you are again using the complete file. So the
grep
succeeds if there is any line withstaff
in it; even if the username would bejohnfalstaff
What you really want to know is if the second column in your line
is staff
, so:
if [ "${line#*,}" = "staff" ] ; then
sudo usermod -a -G staff else sudo usermod -a -G visitors
So, where is the fi
that closes the if
statement?
done < $username
Also, quote the filename: done < "$username"