Todd Alfke
Todd Alfke

Reputation: 21

How to loop through array items and pass each item to a function in bash

How can I pass a single item value from array starting from index/item 0 into function and loop through the array until all items have been passed?

This scripts intended purpose is to pull lines from a text file called array_list and pass them into an array, then perform a function on each array item in a loop until all items have been passed and echo out results to a text file called results.txt showing HTTP Status Codes to associated URL's

#!/bin/bash
#
#Script to lookup URL address and capture associated HTTP Status Code (EG: 200, 301, 400, 404,500, 503)
#
#
declare -a array
array=()
getArray()
    {
    i=0
    while read line
    do
        array[i]=$line
        i=$(($i + 1))
    done < $1
    }
getArray "array_list"
for url in ${array[@]}
do
    function call()
    {
        curl -s -o /dev/null -w "%{http_code}" $url
    }
done

response=$(call)

echo $url $response  >> result.txt

Upvotes: 1

Views: 2495

Answers (2)

Todd Alfke
Todd Alfke

Reputation: 21

Here are the changes I made to get it working. I'll try the way rici has suggested as well.

#!/bin/bash
#Script to lookup URL address and capture associated HTTP Status Code (EG: 200, 301, 400, 404,500, 503)
#
declare -a array
array=()
getArray()
    {
    i=0
    while read line
    do
        array[i]=$line
        i=$(($i + 1))
    done < $1
    }
getArray "array_list"

count=${#array[@]}
index=0
while [ "$index" -lt "$count" ]
do
    #echo -e "index: $index\tvalue: ${array[$index]}"
    for url in ${array[$index]}
    do
         function call()
             {
                curl -s -o /dev/null -w "%{http_code}" $url
             }
    done
    response=$(call)
    echo $url $response  >> result
    let "index++"

done

Upvotes: 0

rici
rici

Reputation: 241721

This is a loop which defines the function curl many times, but never calls it:

for url in ${array[@]}
do
    function call()
    {
        curl -s -o /dev/null -w "%{http_code}" $url
    }
done

It's not obvious why you want a function here. You could just do this:

for url in ${array[@]}; do
  printf "%s " "$url" >> results.txt
  curl -s -o /dev/null -w "%{http_code}" "$url" >> results.txt
done

Of course, you could define the function (taking an argument):

function getfile() {
  curl -s -o /dev/null -w "%{http_code}" "$1"
}

and then call it in a loop:

for url in ${array[@]}; do
  result=$(getfile "$url")
  printf "%s %s\n" "$url" "$result" >> results.txt
done

Not directly related to your question, but:

You entire getArray function already exists as a bash built-in, so you might as well just use it:

mapfiles -t array < array_list

See help mapfiles for more options.

Upvotes: 1

Related Questions