0
echo -n "Enter a positive integer: "; read integer
  While [ $integer -gt 0 ]; do
    echo "$integer"
  done

I am trying to write a script in UNIX that meets the following criteria:

  1. Name the script while.sh.
  2. Ask the user to enter a positive integer. You can assume that the user will enter a positive integer (input validation not required).
  3. Use a while loop to print all integers from 0 up to and including the integer entered.

The first two steps were easy, but I cannot get the third step to execute properly. Can anyone help me?

4
  • 1
    Use expr to increment a variable: x=`expr $x + 1` Commented Apr 7, 2015 at 19:08
  • You need a "counter" variable that starts at 0 and stops when greater than the user's value. Commented Apr 7, 2015 at 19:09
  • I did not know the expr command, that will be useful in the future, thanks for your input. Commented Apr 7, 2015 at 19:32
  • Don't use expr for integer arithmetic; use the POSIX arithmetic expression; x=$((x + 1)). Commented May 2, 2015 at 2:39

2 Answers 2

2

This is the script you want:

#!/bin/bash

echo -n "Enter a positive integer: "; read integer
while [ $integer -gt 0 ]; do
    echo "$integer"
    integer=`expr $integer - 1`
done

This is an example:

./while.sh 
Enter a positive integer: 10
10
9
8
7
6
5
4
3
2
1
Sign up to request clarification or add additional context in comments.

2 Comments

or simply ((--integer))
((--integer)) is not a standard shell command; only some shells will support it. Instead, use integer=$((integer - 1)) or even : $((--integer)).
0

This is the script I came up with. I may have taken this a little to literal, however your question does ask for displaying 0 to the number entered.

#! /bin/bash

i=0

echo -n "Enter a positive integer: "
read integer

while [ $integer -ge $i ]
 do
  echo "$i"
  ((i++))
done

Here is the output from above:

Enter a positive integer: 11
0
1
2
3
4
5
6
7
8
9
10
11

1 Comment

That is another way to think about it. I like your way because it goes in ascending order, rather than descending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.