Home > Net >  How to iterate the number of arguments in a for loop?
How to iterate the number of arguments in a for loop?

Time:10-04

I'm new to bash programming, and I'm trying to implement a for loop that iterates the number of arguments. I tried with "$#" or just "for i", and it didn't work. So, basically, I'm seeking guidance and a way to solve that issue. This is when I execute my script:

./cat.sh food.sh house.sh tv.sh

In my script:

#!/bin/bash
for i in $@
do
echo $i
done

I want to echo

1
2
3

and not

food.sh
house.sh
tv.sh

CodePudding user response:

Assuming the seq binary to be available and taking only the end goal into consideration, one could write something like this.

#!/bin/bash
 
seq $#

I wouldn't personally go for this solution unless I am in for code golf and would rather stick with already posted pure bash solutions.

CodePudding user response:

Keep a running counter outside of the for loop to iterate over the count of arguments.

This should work:

#!/bin/bash

counter=0

for i in $@
do
counter=$((counter 1))
echo $counter
done

Input:

./cat.sh food.sh house.sh tv.sh

Output:

1
2
3

Input:

./cat.sh a b c d e f g

Output:

1
2
3
4
5
6
7

CodePudding user response:

$# contains the number of arguments so one idea OP could use to write the for loop:

for ((i=1; i<=$#; i  ))
do
    echo $i
done

# or

count=$#

for ((i=1; i<=count; i  ))
do
    echo $i
done
  • Related