Score:0

Using variables in for loops bash

bd flag

I was just wondering if it is possible to use variables in for loops?? I tried:

for number in { eval echo {0..$1}}
do 
    echo 5
done

I meant for it to print out 5 the number of times I entered into the prompt however, it acts strangely if I enter in:

./test.sh 2

It should print out 5 two times, but it prints out 5 four times. Can someone help me with this? And also why is it printing out 4 times instead of 2??

Edit: For the most part

for number in $(seq "$2")

Works but If I try a calculation with it, it breaks my code:

time=1
total=5
for number in $(seq "$2")
do
    echo "$time + $total" | bc
done

Gives: seq: invalid floating point argument: ‘’ Try 'seq --help' for more information. Can someone tell me how to fix it??

cc flag
Use backtics (`) instead of the outer { } and your loop should work, but start at 1 instead of 0 for your expected two times through the loop.
hr flag
If you use `seq "$2"` then you need to provide a numeric 2nd positional parameter when you call the script ex. `./test.sh foo 2`
Score:2
hr flag

It prints out 5 four times because { eval echo {0..2}} results in four whitespace-separated tokens {, 0, 1 and 2}

If you want to use $1 as the end of a range expression in bash, it's better to use the external seq command:

for number in $(seq "$1")

or use a C-style for loop

for ((number=0; number<"$1"; number++))
Yunfei Chen avatar
bd flag
It works but If I use variables inside of the for loop it breaks immediately
Yunfei Chen avatar
bd flag
time=1 total=5 for number in $(seq "$2") do echo "$time + $total" | bc done
hr flag
@YunfeiChen fails how, exactly? How are you calling the script? In particular, how many positional parameters are you supplying (since you apparently changed `$1` to `$2`)
Yunfei Chen avatar
bd flag
Gives me:(standard_in) 1: syntax error (standard_in) 1: illegal character: : (standard_in) 1: syntax error (standard_in) 1: syntax error (standard_in) 1: syntax error (standard_in) 2: syntax error (standard_in) 2: illegal character: : (standard_in) 2: syntax error (standard_in) 2: syntax error (standard_in) 2: syntax error
hr flag
@YunfeiChen comments are not the right place for follow-on questions - in particular, the formating doesn't allow me to see what you are actually typing. If the "illegal character" is `^M` then that's because your script has Windows line endings.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.