簡體   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 腳本每 X 秒運行一個簡單的 hello world C 代碼 M 次,其中 X 和 M 是用戶輸入。 當我運行腳本時,for 循環只運行一次。 但是當我用任何數字替換“$M”時,它運行良好。 那么我的錯誤是什么? 如何在 for 循環迭代中提供用戶輸入?

Bash 的大括號擴展發生在評估變量之前。 您可以使用替代的 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