1

In what way does the final value of number being assigned by read var number (and we enter 5) and number=5 differ? I was making this for loop:

read var number
#number=5
factorial=1
i=1
for i in `seq 1 $number`
do
        let factorial=factorial*i
done
echo $factorial

when I noticed that if the number has the value assigned by the read, rather than direct assigning, it doesn't enter my for. I'm guessing it's because of the data type.

  • 2
    Please don't do this in Bash. It's just not the right tool for this job. It's really not a programming language in the sense of dealing with computation, data structures or algorithms; see unix.stackexchange.com/a/303387/135943 (and the links from there) for more details. – Wildcard Mar 18 '17 at 0:45
3

If you change the first line to

read number

you’ll get the behaviour you’re looking for.

read var number

reads two values and stores them in variables named var and number. If you only input one value, seq 1 $number expands to seq 1 which is just 1.

  • Ah, I was mislead by something ambiguous, saying that the syntax for reading is read var [var_1 var_2 var_3 ... var_n]. I thought var was telling the interpreter that they are variables. – Peter Mar 17 '17 at 10:48
  • 1
    @Peter If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Mar 17 '17 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.