0

New to loop bash. I need a script to read a txt file and delete a user on each listed server. How would this look?

for user in $(cat /tmp/server-list.txt); do userdel -f $USERID; done

It fires, but does not find the User account on any of the servers (use 'ID' does not exist). What am I getting wrong?

1
  • 4
    This doesn't make sense. You have a list of servers, loop the list (with a very bad method) and get back users?? And why would a variable $USERID being set? You should share your whole script and tell us the whole picture. This is not answerable.
    – pLumo
    Commented Oct 10, 2022 at 19:39

3 Answers 3

1

Assuming you are:

  1. Trying to loop through a text file with a list of server IP addresses, each one on a new line
  2. SSH to each server as the ubuntu user (feel free to change to your user) and you are trying to delete a single particular user (lets say "john smith") on each machine
  3. All as one line

USERID="john smith"; cat /tmp/server-list.txt | while read IP_ADDRESS; do ssh -q -n ubuntu@$IP_ADDRESS "userdel -f $USERID" ; done

If you have multiple users and multiple servers, you would need to use a nested loop or an array

0

Given that this is Bash, we can use mapfile to create an array from the file contents:

mapfile server </tmp/server-list.txt

Then we can loop over these servers:

for s in "${server[@]}"
do
    #something
done

Now we need to use the value of $s when we write the code where I put the placeholder "#something" (this can be a little tricky, because the "command" arguments to ssh are combined into a string that's passed to sh -c on the server):

    ssh "root@$s" "userdel -f '${USERID//\'/\'\\\'\'}''"

(Assuming $USERID is set somewhere outside the script; that tricky substition is to deal with ' characters that would otherwise confuse the remote shell)

Putting it all together:

read -p "Delete which user?" userid
mapfile server </tmp/server-list.txt
for s in "${server[@]}"
do
    ssh "root@$s" "userdel -f '${userid//\'/\'\\\'\'}''"
done
-2

for user in $(cat /tmp/server-list.txt); do userdel -f $USERID; done

Here user is a name of a loop variable. On each iteration of the loop you are setting it to a next line of /tmp/server-list.txt file.

That variable is not used anywhere in the loop. So the loop will execute same statement over and over as many times as there are lines in the file.

$USERID reads variable USERID which is not set in this piece of code. So, assuming you did not assign anything to this variable, the actual executed code would be

userdel -f

Reading lines from file 'server-list.txt' into variable 'user' is not really an error, but very confusing nonetheless. It is a style mistake which would give you a lot of headache if your loop would grow to a few commands.

1
  • 1
    for user in $(cat ...) does not loop lines but words.
    – pLumo
    Commented Oct 11, 2022 at 7:06

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