简体   繁体   中英

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?

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
for i in $(seq X Y); do ... done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM