Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - Using a variable in brace expansion range fed to a for loop

Here is myscript.sh

#!/bin/bash
for i in {1..$1};
do
    echo $1 $i;
done

If I run myscript.sh 3 the output is

3 {1..3}

instead of

3 1
3 2
3 3

Clearly $3 contains the right value, so why doesn't for i in {1..$1} behave the same as if I had written for i in {1..3} directly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use a C-style for loop to accomplish this:

for ((i=1; i<=$1; i++)); do
   echo $i
done

This avoids external commands and nasty eval statements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...