Darshak Chavda
Darshak Chavda

Reputation: 33

shell script to run for loop N times where N is user input

#!/bin/bash

read -p "Enter X in seconds: " X
read -p "Enter M(no. of times): " M

for i in {1.."$M"};
do
    gcc hello.c -o hello
    ./hello
    sleep "$X"
done;

Shell script to run a simple hello world C code every X seconds for M times, where X and M are user input. When I run the script, for loop runs only one time. But when I replace "$M" with any number, it runs well. So what is my mistake here? How can I give user input in for loop iteration?

Upvotes: 2

Views: 2008

Answers (2)

nickmick
nickmick

Reputation: 1

for i in $(seq X Y); do
  ... 
done

Upvotes: 0

P.P
P.P

Reputation: 121387

Bash's brace expansion happens before variables are evaluated. You can use the alternative C-style loop instead:

for((i=1; i<=M; i++)); do
    ....
done

Upvotes: 1

Related Questions