我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
当前回答
您可以这样使用:
## 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"
)
其他回答
单线循环,
declare -a listOfNames=('db_a' 'db_b' 'db_c')
for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
你会得到这样的输出,
db_a
db_b
db_c
我真正需要的是这样的东西:
for i in $(the_array); do something; done
例如:
for i in $(ps -aux | grep vlc | awk '{ print $2 }'); do kill -9 $i; done
(将终止所有以vlc命名的进程)
试试这个。它正在运行和测试。
for k in "${array[@]}"
do
echo $k
done
# For accessing with the echo command: echo ${array[0]}, ${array[1]}
简单方法:
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}
当然,这是可能的。
for databaseName in a b c d e f; do
# do something like: echo $databaseName
done
有关详细信息,请参阅、while和until的Bash循环。