2015-02-08 84 views
0

如何从索引/项0开始将数组中的单个项传递给函数并遍历数组,直到所有项都已传递为止?如何遍历数组项并将每个项传递给bash中的函数

这个脚本的目的是从一个名为array_list的文本文件中拉出行,并将它们传递给一个数组,然后在循环中的每个数组项上执行一个函数,直到所有项都已传递并将结果回显为文本文件所谓RESULTS.TXT显示到相关网址的

#!/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 
+0

我不是bash大师,但它看起来像你一次又一次地声明相同的功能与不同的网址。 – alfasin 2015-02-08 02:51:03

回答

1

HTTP状态代码这是一个循环定义功能curl很多次,但从来没有将其称为:

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

为什么你想有一个函数这不是很明显这里。你可能只是这样做:

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

当然,你可以定义函数(取参数):

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

,然后把它在一个循环:

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

与您的问题没有直接关系,但是:

你整个getArray功能已经存在了内置在bash,所以你可能也只是使用它:

mapfiles -t array < array_list 

查看更多选项见help mapfiles

+1

感谢rici,我是一个新手,可能没有最佳做法。我感谢你的回应。 – 2015-02-08 06:44:59

0

以下是我为了使其工作而做出的更改。我会尝试rici建议的方式。

#!/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 
相关问题