数组基础 Shell 脚本 |设置 2(使用循环)
建议通过Array Basics Shell Scripting |组 1
介绍
假设您想多次重复特定任务,那么最好使用循环。大多数语言都提供循环的概念。在 Bourne Shell 中有两种类型的循环,即for
循环和while
循环。
在 Bash 中打印静态数组
1.通过使用while循环
${#arr[@]}
用于查找 Array 的大小。
# !/bin/bash
# To declare static Array
arr=(1 12 31 4 5)
i=0
# Loop upto size of array
# starting from index, i=0
while [ $i -lt ${#arr[@]} ]
do
# To print index, ith
# element
echo ${arr[$i]}
# Increment the i = i + 1
i=`expr $i + 1`
done
输出:
1
2
3
4
5
2. 使用for循环
# !/bin/bash
# To declare static Array
arr=(1 2 3 4 5)
# loops iterate through a
# set of values until the
# list (arr) is exhausted
for i in "${arr[@]}"
do
# access each element
# as $i
echo $i
done
输出:
1
2
3
4
5
在运行时读取数组元素,然后打印数组。
1.使用While循环
# !/bin/bash
# To input array at run
# time by using while-loop
# echo -n is used to print
# message without new line
echo -n "Enter the Total numbers :"
read n
echo "Enter numbers :"
i=0
# Read upto the size of
# given array starting from
# index, i=0
while [ $i -lt $n ]
do
# To input from user
read a[$i]
# Increment the i = i + 1
i=`expr $i + 1`
done
# To print array values
# starting from index, i=0
echo "Output :"
i=0
while [ $i -lt $n ]
do
echo ${a[$i]}
# To increment index
# by 1, i=i+1
i=`expr $i + 1`
done
输出:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
2.使用for循环
# !/bin/bash
# To input array at run
# time by using for-loop
echo -n "Enter the Total numbers :"
read n
echo "Enter numbers:"
i=0
# Read upto the size of
# given array starting
# from index, i=0
while [ $i -lt $n ]
do
# To input from user
read a[$i]
# To increment index
# by 1, i=i+1
i=`expr $i + 1`
done
# Print the array starting
# from index, i=0
echo "Output :"
for i in "${a[@]}"
do
# access each element as $i
echo $i
done
输出:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5