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

类似于:

for databaseName in listOfNames
then
  # Do something
end

当前回答

声明数组不适用于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

其他回答

当然,这是可能的。

for databaseName in a b c d e f; do
  # do something like: echo $databaseName
done 

有关详细信息,请参阅、while和until的Bash循环。

简单方法:

arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array

len=${#arr[*]}  # it returns the array length

#iterate with while loop
i=0
while [ $i -lt $len ]
do
    echo ${arr[$i]}
    i=$((i+1))
done


#iterate with for loop
for i in $arr
do
  echo $i
done

#iterate with splice
 echo ${arr[@]:0:3}

这也很容易阅读:

FilePath=(
    "/tmp/path1/"    #FilePath[0]
    "/tmp/path2/"    #FilePath[1]
)

#Loop
for Path in "${FilePath[@]}"
do
    echo "$Path"
done

循环遍历数组的方式取决于换行符的存在。使用分隔数组元素的换行符,数组可以称为“$array”,否则应称为“${array[@]}”。以下脚本将明确说明:

#!/bin/bash

mkdir temp
mkdir temp/aaa
mkdir temp/bbb
mkdir temp/ccc
array=$(ls temp)
array1=(aaa bbb ccc)
array2=$(echo -e "aaa\nbbb\nccc")

echo '$array'
echo "$array"
echo
for dirname in "$array"; do
    echo "$dirname"
done
echo
for dirname in "${array[@]}"; do
    echo "$dirname"
done
echo
echo '$array1'
echo "$array1"
echo
for dirname in "$array1"; do
    echo "$dirname"
done
echo
for dirname in "${array1[@]}"; do
    echo "$dirname"
done
echo
echo '$array2'
echo "$array2"
echo
for dirname in "$array2"; do
    echo "$dirname"
done
echo
for dirname in "${array2[@]}"; do
    echo "$dirname"
done
rmdir temp/aaa
rmdir temp/bbb
rmdir temp/ccc
rmdir temp

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

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不需要引用,因为它们只是数字;有些人会建议引用它们,但这只是个人偏好。)