Linux Shell array length calculation, modification, cyclic output, and other operations

Source: Internet
Author: User

From: http://blog.csdn.net/snrqtdhuqf/article/details/7242309

In shell, there are two ways to assign values to array variables:

(1) name = (value1... valuen) The subscript starts from 0.

(2) name [Index] = Value

Example:

    1. #! /Bin/sh
    2. # Arraytest
    3. Name = (yunix yhx YFJ)
    4. Echo "array is :$ {name [@]}"
    5. Echo "array length is :$ {# name [*]}"
    6. Echo $ {name [1]}
    7. Name [1] = Yang
    8. Echo $ {name [1]}
    9. Read-a name
    10. Echo $ {name [1]}
    11. Echo "loop the array"
    12. Len = $ {# name [*]}
    13. I = 0
    14. While [$ I-lt $ Len]
    15. Do
    16. Echo $ {name [$ I]}
    17. Let I ++
    18. Done

Result:

Array is: yunix yhx YFJ
Array length is: 3
Yhx
Yang
A B C D E
B
Loop the Array
A
B
C
D
E

 

The following is an array output example.

Example:

#! /Bin/sh

  1. # Arrayloopout
  2. Read-A Array
  3. Len =$ {# array [*]}
  4. Echo "array's length is $ len"
  5. Echo "use while out the array :"
  6. I = 0
  7. While [$ I-lt $ Len]
  8. Do
  9. Echo-n "$ {array [$ I]}"
  10. Let I ++
  11. Done
  12. Echo
  13. Echo "use for out the array :"
  14. For (j = 0; j <"$ len"; j = J + 1 ))
  15. Do
  16. Echo-N $ {array [$ J]}
  17. Done
  18. Echo
  19. Echo "use for in out the array :"
  20. For value in $ {array [*]}
  21. Do
  22. Echo-N $ Value
  23. Done

Result:

a B C D E F G
array's length is 7
use while out the array:
abcdefg
use for out the array:
abcdefg
use for in out the array:
abcdefg

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.