2

Okay, so I been trying to figure this problem for a while and I'm coming up with errors left and right. This is my first time trying to learn the basics. So any advice would be helpful!

Problem: I'm trying to write a Bash shell script program that prompts for and reads two integers from the user. The second argument is assumed to be greater than the first. The output of the program is a counting of numbers beginning at the first number and ending with the second number.

In other words the output would look like this:

    Please enter the first number:
    3
    Please enter the second number, larger than the first:
    6

    3
    4
    5
    6

Okay, so this is what I have so far~

    read -p "Please Enter the first number : " n1
     echo "$n1"
   read -p "Please Enter the second number, larger than the first : " n2
     echo "$n2"
   FIRSTV=0
   SECONDV=1
   if [ 1 -gt 0]
   then
   count=$((FIRSTV-SECONDV))
   echo $COUNT
   fi
2

If you can use seq, you could do this:

read -p "Please Enter the first number : " n1
echo "$n1"
read -p "Please Enter the second number, larger than the first : " n2
echo "$n2"

seq "$n1" "$n2"

If you have to do it entirely in shell and can use a modern shell like bash, ksh, zsh etc (but not ash or dash or similar strictly POSIX shell), you could replace the seq command with:

eval "printf '%s\n' {$n1..$n2}"

You need to use eval for the second version because bash/ksh/etc sequences expect actual integers like {1..5}, not variables like {$n1..$n2}. eval expands the variables so that their actual values are used inside the {...} sequence.

if you want to do it with a loop and no fancy bash/ksh/etc features, you could replace the seq or eval lines with something like:

c="$n1"

while [ "$c" -le "$n2" ] ; do
    echo "$c"
    c=$((c+1))
done

This works in any POSIX-compatible shell, including dash and ash, as well as bash etc.

  • Thank you for replying! I can use bash. So i'm going to give it a try right now! – Linda Apr 23 '16 at 4:40
  • I try it just now and it worked perfectly! Thank you so much for your help! I was way off on the second part!But now I know – Linda Apr 23 '16 at 4:43
  • BTW, if you want the output all on one line rather than each number on its own line, use echo rather than printf '%s\n' – cas Apr 23 '16 at 4:43
  • printf '%s\n' works for what I need. However, this is a helpful hint for my next problem! Thanks! – Linda Apr 23 '16 at 4:45
  • you weren't completely off with the second part. bash can do arithmetic, and you can combine that with a loop. but seq exists, and bash also has built-in support for integer sequences - using either of them is easier and faster. if you're trying to teach yourself, seeing how to do it with a loop is a useful. – cas Apr 23 '16 at 4:45

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.