Linux basic shell array

Posted by foobar on Mon, 04 May 2020 01:49:51 +0200

abstract

The property of array is a set of collection with the same data type. Although the shell is of weak type, we can also divide its array into data type array and string type array
The shell's array elements are separated by spaces

Array operation

Suppose you have two arrays

array1=(1 2 3 4 5 6)
array2=("James" "Colin" "Harry")
  • Data variable name default output
    If a variable is output directly by default, its output value is the value of the first element by default, and the subscript starts from 0
root@pts/1 $ echo $array1
1
root@pts/1 $ echo $array2
James
  • Get array elements
    Format: ${array name [subscript]}, subscript starts from 0, subscript * or @ represents the whole array content
root@pts/1 $ echo ${array1[2]}
3
root@pts/1 $ echo ${array2[1]}
Colin

## Get all elements
root@pts/1 $ echo ${array2[*]}
James Colin Harry
root@pts/1 $ echo ${array2[@]}
James Colin Harry
  • Get array length
    Format: ${ා array name [* or @]}
root@pts/1 $ echo ${#array1[@]}
6
root@pts/1 $ echo ${#array2[*]}
3
  • Array traversal
root@pts/1 $ for item in ${array2[@]}
> do
>     echo "The name is ${item}"
> done
The name is James
The name is Colin
The name is Harry
  • Array element assignment

Format: array name [subscript] = value. If the subscript does not exist, the array element will be added; if the subscript already exists, the array element value will be overwritten

root@pts/1 $ array1[2]=18
root@pts/1 $ echo ${array1[*]}
1 2 18 4 5 6

root@pts/1 $ array2[4]="Betty"
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
  • Array slice

Format: ${array name [* or @]: start bit: length}, truncate part of array, return string, separated by spaces; use () to get new slice array

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]:1:3}
Colin Harry Betty

root@pts/1 $ array3=(${array2[*]:1:2})
ks-devops [~] 2018-01-25 20:30:16
root@pts/1 $ echo ${array3[@]}
Colin Harry
  • Array element replacement

Format: ${array name [* or @] / find character / replace character}, the original array will not be modified; if you want to modify the array, use "()" to assign the result to the new array

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]/Colin/Colin.Liu}
James Colin.Liu Harry Betty

root@pts/1 $ array4=(${array2[*]/Colin/Colin.liu})
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty
  • Delete element

Format:
unset array, clear the whole array;
unset array [subscript], clear single element

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty

root@pts/1 $ unset array4
root@pts/1 $ unset ${array2[3]}

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty

root@pts/1 $ echo ${array4[*]}

root@pts/1 $

Topics: shell