我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?

类似于:

for databaseName in listOfNames
then
  # Do something
end

当前回答

很惊讶还没有人发布这个消息——如果在遍历数组时需要元素的索引,可以这样做:

arr=(foo bar baz)

for i in ${!arr[@]}
do
    echo $i "${arr[i]}"
done

输出:

0 foo
1 bar
2 baz

我发现这比“传统”for循环样式(for((I=0;I<${#arr[@]};I++))要优雅得多。

(${!arr[@]}和$i不需要引用,因为它们只是数字;有些人会建议引用它们,但这只是个人偏好。)

其他回答

您可以这样使用:

## declare an array variable
declare -a arr=("element1" "element2" "element3")

## now loop through the above array
for i in "${arr[@]}"
do
   echo "$i"
   # or do whatever with individual element of the array
done

# You can access them using echo "${arr[0]}", "${arr[1]}" also

也适用于多行数组声明

declare -a arr=("element1" 
                "element2" "element3"
                "element4"
                )

您可以使用${arrayName[@]}的语法

#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
    echo "$i"
done

我在GitHub更新中使用了这种方法,我发现它很简单。

## declare an array variable
arr_variable=("kofi" "kwame" "Ama")

## now loop through the above array
for i in "${arr_variable[@]}"
do
   echo "$i"


done
   

您可以使用带有三个表达式(C样式)的计数器遍历bash数组值,以读取循环语法的所有值和索引:

declare -a kofi=("kofi" "kwame" "Ama")
 
# get the length of the array
length=${#kofi[@]}

for (( j=0; j<${length}; j++ ));
do
  print (f "Current index %d with value %s\n" $j "${kofi[$j]}")
done

声明数组不适用于Korn shell。对Korn shell使用以下示例:

promote_sla_chk_lst="cdi xlob"

set -A promote_arry $promote_sla_chk_lst

for i in ${promote_arry[*]};
    do
            echo $i
    done

很惊讶还没有人发布这个消息——如果在遍历数组时需要元素的索引,可以这样做:

arr=(foo bar baz)

for i in ${!arr[@]}
do
    echo $i "${arr[i]}"
done

输出:

0 foo
1 bar
2 baz

我发现这比“传统”for循环样式(for((I=0;I<${#arr[@]};I++))要优雅得多。

(${!arr[@]}和$i不需要引用,因为它们只是数字;有些人会建议引用它们,但这只是个人偏好。)