我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
当前回答
简单方法:
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}
其他回答
这些答案中没有一个包含计数器。。。
#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")
# get length of an array
arraylength=${#array[@]}
# use for loop to read all values and indexes
for (( i=0; i<${arraylength}; i++ ));
do
echo "index: $i, value: ${array[$i]}"
done
输出:
index: 0, value: one
index: 1, value: two
index: 2, value: three
您可以使用${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
这与user2533809的答案类似,但每个文件都将作为单独的命令执行。
#!/bin/bash
names="RA
RB
R C
RD"
while read -r line; do
echo line: "$line"
done <<< "$names"
简单方法:
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}