简体   繁体   English

运行循环 N 次的 shell 脚本,其中 N 是用户输入

[英]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. Shell 脚本每 X 秒运行一个简单的 hello world C 代码 M 次,其中 X 和 M 是用户输入。 When I run the script, for loop runs only one time.当我运行脚本时,for 循环只运行一次。 But when I replace "$M" with any number, it runs well.但是当我用任何数字替换“$M”时,它运行良好。 So what is my mistake here?那么我的错误是什么? How can I give user input in for loop iteration?如何在 for 循环迭代中提供用户输入?

Bash's brace expansion happens before variables are evaluated. Bash 的大括号扩展发生在评估变量之前。 You can use the alternative C-style loop instead:您可以使用替代的 C 样式循环:

for((i=1; i<=M; i++)); do
    ....
done
for i in $(seq X Y); do ... done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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