Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux bash script - For loops issues

I'm working on a bash script that will add users in a batch process. This code goes as follows:

#!/bin/bash
# A script that creates users.

echo "This is a script to create new users on this system."
echo "How many users do you want to add?"
read am
echo " "

for i in {0..$am..1}
do
    echo "Enter a username below:"
    read usern
    sudo useradd $usern

    sudo passwd $usern

    echo " "
    echo "User $am '$usern' added."
done

In this case, I wanted to make 4 users. I went through and entered the username "callum3" and set the password as "1234" for ease of login. Once I input everything (correctly, may I add) the terminal window displays the following.

User 4 'callum3' added.

This shows that my for loop isn't actually working, when I can see nothing wrong with it. I have tried using a while loop with no luck there either.

Am I making a rookie mistake here or is there something deeper going on?

like image 307
CallumWale Avatar asked May 11 '26 10:05

CallumWale


2 Answers

Although I suspected it, for a better understanding on what could be wrong with your script I pasted it in shellcheck.net. That the problem is in the line:

for i in {0..$am..1}

Bash doesn't support variables in brace range expansions. That is, you cannot use a variable in an expression like {..}.

Instead, use seq. With seq $var you get a sequence from 1 (default) to $var:

for i in $(seq "$am")
like image 131
fedorqui 'SO stop harming' Avatar answered May 14 '26 14:05

fedorqui 'SO stop harming'


I feel like I'm missing something in that nobody has suggested an arithmetic for loop:

for ((i=0; i<am; i++)); do
    …
done

This has the particular benefit in bash of being both readable and not requiring a subshell.

like image 21
kojiro Avatar answered May 14 '26 14:05

kojiro