当前位置:网站首页>Shell array

Shell array

2022-06-24 08:37:00 Chen Bucheng I

You can store multiple values in an array .Bash Shell Only one-dimensional arrays are supported ( Multidimensional arrays are not supported ), There is no need to define the array size when initializing ( And PHP similar ). Similar to most programming languages , The subscripts of array elements are 0 Start .

Create array

Shell Arrays are represented in parentheses , Element use ” Space ” Symbol split , The syntax is as follows : array_name=(value1 value2 ... valuen) example

  1. #!/bin/bash
  2. my_array=(A B "C" D)
  3. We can also use subscripts to define arrays :
  4. array_name[0]=value0
  5. array_name[1]=value1
  6. array_name[2]=value2

Read array

The general format for reading array element values is : ${array_name[index]}

  1. example
  2. #!/bin/bash
  3. my_array=(A B "C" D)
  4. echo " The first element is : ${my_array[0]}"
  5. echo " The second element is : ${my_array[1]}"
  6. echo " The third element is : ${my_array[2]}"
  7. echo " The fourth element is : ${my_array[3]}"

Execute the script , The output is as follows :

  1. $ chmod +x test.sh
  2. $ ./test.sh
  3. The first element is : A
  4. The second element is : B
  5. The third element is : C
  6. The fourth element is : D

Get all the elements in the array

Use @ or * You can get all the elements in the array for example :

  1. #!/bin/bash
  2. my_array[0]=A
  3. my_array[1]=B
  4. my_array[2]=C
  5. my_array[3]=D
  6. echo " The elements of the array are : ${my_array[*]}"
  7. echo " The elements of the array are : ${my_array[@]}"

Execute the script , The output is as follows :

  1. $ chmod +x test.sh
  2. $ ./test.sh
  3. The elements of the array are : A B C D
  4. The elements of the array are : A B C D

Gets the length of the array

The way to get the array length is the same as the way to get the string length for example :

  1. #!/bin/bash
  2. my_array[0]=A
  3. my_array[1]=B
  4. my_array[2]=C
  5. my_array[3]=D
  6. echo " The number of array elements is : ${#my_array[*]}"
  7. echo " The number of array elements is : ${#my_array[@]}"

Execute the script , The output is as follows :

  1. $ chmod +x test.sh
  2. $ ./test.sh
  3. The number of array elements is :4
  4. The number of array elements is :4
原网站

版权声明
本文为[Chen Bucheng I]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210622172021034m.html