R
R
Resolut2021-09-06 18:31:08
bash
Resolut, 2021-09-06 18:31:08

How to write a small bash script to create users?

You need to write a script that will create a new user user_[N+1]

#!/bin/bash

N = $(($N+1))
sudo useradd user_$N -p pass_$N
echo "User added!"


I will be glad for any help!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xotkot, 2021-09-06
@lxst

it feels like the condition is incomplete, so I’ll complicate it a little, and if you wish, you can easily simplify the script to the desired result
. Suppose you need to create N users (from 1 to N) and set a password for them, and all this with the corresponding numerical prefix . That is, write a script that receives a base name and password as input, as well as the number of users that need to be created.
let's say the script name is luser.sh

#!/usr/bin/env bash

USER=$1 # базовая часть имени пользователя
PASS=$2 # базовая часть пароля
N=$3    # количество пользователей
for (( i = 1; i <= $N; i++ )); do
  useradd "${USER}_$i" && $(echo "${USER}_$i:${PASS}_$i" |chpasswd)
  echo "User ${USER}_$i added!"
done

script example:
$ sudo ./luser.sh user pass 3
User user_1 added!
User user_2 added!
User user_3 added!

check that users with a base in the name user have actually been created:
$ grep -e "^user" /etc/passwd
user_1:x:1314:1314::/home/user_1:/bin/bash
user_2:x:1315:1315::/home/user_2:/bin/bash
user_3:x:1316:1316::/home/user_3:/bin/bash

V
Viktor Taran, 2021-09-06
@shambler81

#!/bin/bash
for ((i=1; i < 10; i++))
do
echo $i
done

Snimok-ekrana-iz-2017-03-11-19-13-09-768x432.png

I
Ivan Koryukov, 2021-09-06
@MadridianFox

I would like more details, because it is not entirely clear how the script will be used and, accordingly, what exactly it should do.
I will assume that when the script is called, one new user with a template name should be created.
Those. you need to somehow get a list of such users from the system, find the last one, take a number from it and increase it by one.
If you definitely need a monotonically increasing number, then something like this:

lastUserSuffix=$(cat /etc/passwd | awk 'BEGIN {FS=":"}; {print $1}' | grep systemd | sort -n | sed 's/systemd-//' | tail -1)

I'm looking for users named systemd-*** here, I think it will not be difficult for you to modify the example for your own purposes.

A
Alexey Pyanov, 2021-10-11
@gohdan

It is better not to use useradd, it gives too extended rights to the home directory (access not only to the user, but to his entire group). Use adduser.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question