LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Need help numbering my arguments (https://www.linuxquestions.org/questions/programming-9/need-help-numbering-my-arguments-4175438659/)

LBP74 11-25-2012 12:35 PM

Need help numbering my arguments
 
I have to write a program that precedes each argument with the line number.

while [ "$#" -ne 0 ]
do

echo $# :"$1"
shift

done
This is what I have but the numbering is in reverse order

]$ prargs a b c d
4 :a
3 :b
2 :c
1 :d
This is my output, I have tried different things but nothing works

markush 11-25-2012 02:37 PM

Hello LBP74, welcome to LQ,

your shift command decrements the number of arguments. And this are your linenumbers, decremented from 4 down to 1.

You could as an alternative set a variable which you increment in each step of the loop.

this would work:
Code:

#!/bin/bash

a=1
while [ "$#" -ne 0 ]; do
        echo "$a":$1
        let a=a+1
        shift
done

Markus

LBP74 12-05-2012 04:05 PM

Quote:

Originally Posted by LBP74 (Post 4836701)
I have to write a program that precedes each argument with the line number.

while [ "$#" -ne 0 ]
do

echo $# :"$1"
shift

done
This is what I have but the numbering is in reverse order

]$ prargs a b c d
4 :a
3 :b
2 :c
1 :d
This is my output, I have tried different things but nothing works

I actually figured out this problem

i=1
while [ "$#" -ne 0 ]
do

echo $i :"$1"
i=$((i + 1))
shift

done
~
I just had to put in a variable to help with the counting of the lines!


All times are GMT -5. The time now is 12:37 AM.