Shell array
Shell array
Application scenario:
Get the length of the array Get the length of the
element
Traverse elements
Element slice
Element replacement
Element deletion
...
Array definition method
Method 1: Array name=(vlaue0 value1 value2 …)
Method 2: Array name=([0]=value[1]=value[2]=value…)
Method 3:
List name=“value 0 value1 value 2..."
Array name = ($list name)
Method 4:
Array name [0] = "value"
Array name [1] = "value"
Array name [2] = "value"
data type included in the array
Numerical type
Character type
Use ""or" to define
operating
Get array
${array name[@/]}
Get the length of the array
${array name#[@/*]}
[root@server6 ~]# echo ${
#a[@]}
5
[root@server6 ~]#
Read a subscript assignment
${array name[subscript]}
[root@server6 ~]# echo ${
a[1]}
2
[root@server6 ~]#
Array traversal
[root@server6 ~]# vim szbl.sh
#!/bin/bash
# 数组遍历
a=(1 2 3 4 5)
for num in ${
a[*]}
do
echo $num
done
[root@server6 ~]# chmod +x szbl.sh
[root@server6 ~]# ./szbl.sh
1
2
3
4
5
[root@server6 ~]#
Array slice
${array name[@/*]: starting position: length}
array replacement
${array name[@/ *]/find character/replace character}
array delete
unset
Shell script debugging
Echo command
bash command
Command syntax
sh [-nvx] Script name
-n: The script will not be executed. It only queries whether there is a problem with the script syntax. If there is no syntax problem, nothing will be displayed. If there is a problem, an error will be prompted.
-v: When executing the script, first output the content of the script to the screen and then there is an error, and an error message will also be given.
-x: Output the content of the executed script to the screen. This is a useful parameter for debugging.
set command
set -x: turn on the adjustment mode
set +x: turn off the adjustment mode
Bubble Sort
small case
Requirements: comparison of given values in the shell
[root@server6 ~]#vim maopao.sh
#!/bin/bash
# 冒泡排序
score=(70 30 40 100 50 60)
for ((i=1;i<${
#score[*]};i++))
do
for ((j=0;j< ${
#score[*]}-$i;j++))
do
if [ ${
score[j]} -gt ${
score[j+1]} ]
then temp=${
score[j]}
score[j]=${
score[$(($j+1))]}
score[$(($j+1))]=$temp
fi
done
done
echo ${
score[*]}
[root@server6 ~]#chmod +x maopao.sh
[root@server6 ~]#./maopao.sh
30 40 50 60 70 100
Another small project
Requirements: Comparison of keyboard input array values
[root@server6 ~]#vim maopao.sh
#!/bin/bash
# 键盘输入冒泡排序
k=0
while true
do
read -p "是否需要输入数值?" do
if [ $do == "no" ]
then break
fi
read -p "请输入第$(($k+1))个元素" key
score[$k]=$key
let k++
done
for ((i=1;i<${
#score[*]};i++))
do
for ((j=0;j< ${
#score[*]}-$i;j++))
do
if [ ${
score[j]} -gt ${
score[j+1]} ]
then temp=${
score[j]}
score[j]=${
score[$(($j+1))]}
score[$(($j+1))]=$temp
fi
done
done
echo ${
score[*]}
[root@server6 ~]#chmod +x maopao.sh
[root@server6 ~]#./maopao.sh
是否需要输入数值?y
请输入第1个元素40
是否需要输入数值?y
请输入第2个元素47
是否需要输入数值?y
请输入第3个元素29
是否需要输入数值?y
请输入第4个元素90
是否需要输入数值?y
请输入第5个元素74
是否需要输入数值?y
请输入第6个元素20
是否需要输入数值?y
请输入第7个元素82
是否需要输入数值?no
20 29 40 47 74 82 90