CallumWale
CallumWale

Reputation: 33

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?

Upvotes: 3

Views: 124

Answers (3)

Jahid
Jahid

Reputation: 22428

You can use:

for i in `seq 0 $((am-1))`
do
...
done

Sequence will start from 0 and end at $am-1

Upvotes: 0

fedorqui
fedorqui

Reputation: 289495

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")

Upvotes: 1

kojiro
kojiro

Reputation: 77059

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.

Upvotes: 1

Related Questions