need an explanation on this script...

The following script will create a directory in a directory and will go on as many times as the number you will give in.

I am trying to find out how it works ... can someone please help me with that?

#!/bin/sh
#create a variable and set it to 1
n=1                     
#start a loop as long as $n is less or equal then 1 just keep on running      
while [ $n -le $1 ] 
#start the loop
do
  #set a variable so that the directory can be variable as well 
  dir=map_$n
  #create the directory "map_$n"
  #if the directory is created "cd" into it
  #otherwise exit the script
  mkdir "$dir" && cd "$dir" || exit 1
  #do a +1 on $n
  n=$(( $n + 1 ))
done

I have commented out what I understand ...
But here is the thing.
How does the script know when it needs to go to exit?

You misunderstood this line. It runs what's between do and done, as long as $n is lower or equal than the first argument (i.e. $1) of the script.

1 Like

So lets say I execure the script with the number 3
./script.sh 3
it will see that $n = 3
So when this is the case it will run what is between "do" and "done"
so it creates a directory "map_1" because $n=1
and then it moves into the directory and it is doing a +1 to $n and it creates another directory ...

But how does the script knows how to stop at 3?

No. $1 will equal 3. $1 is the first argument used when you invoke the command. $2 is the second. $3 is the third. And so on.

$n is a counter set to 1 which is incremented until its value is no longer less than or equal to $1 (the first argument to the script, which in your example is 3).

Regards,
Alister