1

I'm very new to bash and Linux and I was wondering how I could make a bash loop so that when it runs, it will ask you how many times to run, and it will run that many times.

I did it in LUA but I want it to be in bash so it can be added to the ~/.bashrc file so it starts when I connect to my VPS via ssh. Here is the lua code I wrote:

    write("How many times should I loop? ")
local Num = tonumber( read() )
for i=1,Num do
   print("Looped "..tostring(i).." time(s).")
end

Here is the little thing I will add to my ~/.bashrc:

if [[ -n $SSH_CONNECTION ]] ; then
echo example
fi
  • Note that, depending on your distribution, the ~/.bashrc file won't be read when connecting via ssh. I would suggest you use ~/.profile instead. – terdon Apr 12 '15 at 9:51
2

Here is a one liner:

read -p "No of Repetitions?" repeat; for i in $(seq $repeat); do echo "This is $i"; done

If you want to run this if $SSH_CONNECTION is non-empty:

[[ -n $SSH_CONNECTION ]] && read -p "No of Repetitions?" repeat; for i in $(seq $repeat); do echo "This is $i"; done
  • && indicates to run the next command only if the previous one is successful ($?=0)

  • read -p "No of Repetitions?" repeat will prompt "No of Repetitions?" and save the input as repeat variable.

  • for i in $(seq $repeat); do echo "This is $i"; done this for loop will use seq to loop specified number of times to get the job done. You should replace echo "This is $i" with whatever operation you want to perform.

This can be elaborated as:

if [[ -n $SSH_CONNECTION ]]; then
        read -p "No of Repetitions?" repeat
fi

for i in $(seq $repeat); do
        echo "This is $i" 
done
1

See if this helps:

#!/bin/bash
echo -n "How many times should I run? "
read numOfTimes
for i in $(seq 1 $numOfTimes);do
echo $i
done

Let's split the explanation into parts:

  • echo -n presents the message in the screen and reads the user's response into variable numOfTimes.
  • A bash for loop has the following structure: for i in [1 2 3 4 ... n ]; do X; done
  • In this case, I create the sequence 1 2 3 4 ... n using seq, to which you feed 1 as starting number and the last element, represented by the value of $numOfTimes.

Of course in a more complex scenario you should check whether the user's response is numeric and greater than zero, for example, but I think that this example will do the trick for what you want to accomplish.

Source: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.