Summary
The attribute of an array is a set of identical data types, although the shell is a weak type, but we can also divide its array into 数据类型的数组
字符串类型的数组
two categories
Separating the shell array elements from each other 空格
Array manipulation
Assume that there are two of the following arrays
array1=(1 2 3 4 5 6)array2=("James" "Colin" "Harry")
- Data variable name default output
Default direct output variable, its output value defaults to the value of the first element, the subscript 0
starts from
[email protected]/1 $ echo $array11[email protected]/1 $ echo $array2James
- Get array elements
Format: ${数组名[下标]}
, subscript starts with 0, subscript *
or @
represents the entire array content
[email protected]/1 $ echo ${array1[2]}3[email protected]/1 $ echo ${array2[1]}Colin## 获取全部元素[email protected]/1 $ echo ${array2[*]}James Colin Harry[email protected]/1 $ echo ${array2[@]}James Colin Harry
- Get array length
Format:${#数组名[*或@]}
[email protected]/1 $ echo ${#array1[@]}6[email protected]/1 $ echo ${#array2[*]}3
Format: 数组名[下标]=值
If the subscript does not exist, the subscript 新增数组元素
already exists, then覆盖数组元素值
[email protected]/1 $ array1[2]=18[email protected]/1 $ echo ${array1[*]}1 2 18 4 5 6[email protected]/1 $ array2[4]="Betty"[email protected]/1 $ echo ${array2[*]}James Colin Harry Betty
Format: ${数组名[*或@]:起始位:长度}
, intercept part of the array, return the string, separated by a space, and use the result ()
to get a new slice array
[email protected]/1 $ echo ${array2[*]}James Colin Harry Betty[email protected]/1 $ echo ${array2[*]:1:3}Colin Harry Betty[email protected]/1 $ array3=(${array2[*]:1:2})ks-devops [~] 2018-01-25 20:30:16[email protected]/1 $ echo ${array3[@]}Colin Harry
- Array element substitution
Format: ${数组名[*或@]/查找字符/替换字符}
, does not modify the original array; If you want to modify the array, assign the result to the new array using "()"
[email protected]/1 $ echo ${array2[*]}James Colin Harry Betty[email protected]/1 $ echo ${array2[*]/Colin/Colin.Liu}James Colin.Liu Harry Betty[email protected]/1 $ array4=(${array2[*]/Colin/Colin.liu})[email protected]/1 $ echo ${array4[*]}James Colin.liu Harry Betty
Format:
unset 数组
, clears the entire array;
unset 数组[下标]
, clear a single element
[email protected]/1 $ echo ${array2[*]}James Colin Harry Betty[email protected]/1 $ echo ${array4[*]}James Colin.liu Harry Betty[email protected]/1 $ unset array4[email protected]/1 $ unset ${array2[3]}[email protected]/1 $ echo ${array2[*]}James Colin Harry Betty[email protected]/1 $ echo ${array4[*]}[email protected]/1 $
Linux Basics-Shell arrays