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 with staff
in it; even if the username would be johnfalstaff
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"