-4

I would like to print something as 5,4,3,2,1.

This is my program, but it prints the numbers vertically.

numbers=5
i=1
while [ "$i" -le "$numbers" ]
do
echo “$i”
i=$(( $i + 1 ))
done

Do you have any solution that could help me?

aleroy
  • 133
  • 1
    echo '5,4,3,2,1' — this is the simplest answer that can work, as the question is stated. – ctrl-alt-delor Jul 18 '14 at 08:58
  • 1
    echo has a -n option – ctrl-alt-delor Jul 18 '14 at 08:59
  • 2
    @HalosGhost no it's not. Asking for help on shell scripting is explicitly on topic. Whatever made you think it's not? What we don't like is people asking us to write their code for them when they haven't put any effort into it. Questions about shell scripting make up a large percentage of what we deal with here. – terdon Jul 18 '14 at 09:15
  • @terdon, you are correct; I don't know what led me to that conclusion; I was just about to remove my earlier comment, but it appears it has already been removed. Thank you! – HalosGhost Jul 18 '14 at 16:50
  • 1
    @HalosGhost yes, I deleted it to avoid confusion. I also cleared up the rest of our conversation to keep the question tidy. And don't worry about it, we all get confused about the scope of the various SE sites :). – terdon Jul 18 '14 at 17:16

2 Answers2

4

There are many ways to do this, here are some:

  1. Use seq as @Gnouc suggested.

  2. Use brace expansion and convert spaces to commas:

    $ echo {5..1} | sed 's/ /,/g' 
    5,4,3,2,1
    
  3. Use your script but change decrement the counter instead of incrementing it and change echo to echo -n (this will work for bash's builtin echo but not for all echo implementations):

    i=5
    while [ "$i" -gt 1 ]
    do
        echo -n "$i,"
        let i--
    done
    echo "$i"    
    
  4. Use printf instead:

    i=5
    while [ "$i" -gt 1 ]
    do
        printf "%s," "$i"
        let i--
    done
    printf "%s\n" "$i"    
    
  5. Use a variable:

    i=5
    v=5
    while [ "$i" -gt 1 ]
    do
        let i--;
        v=$v,$i
    done
    echo $v
    
terdon
  • 242,166
3

With seq, you can do:

$ seq -s, 5 -1 1
5,4,3,2,1

And a perl solution can be portable:

$ perl -e 'print join ",", reverse 1..5'
cuonglm
  • 153,898