Introduction to Shell Array usage

Source: Internet
Author: User
Tags array length

Introduction to Arrays

Bash provides only one-dimensional arrays, and does not qualify the size of the array. Similar to the C language, the subscript of an array element is numbered starting with 0. Gets the elements in the array to take advantage of the subscript. The subscript can be an integer or an arithmetic expression whose value should be greater than or equal to 0. You can assign values to an array variable using an assignment statement.

Array Assignment
    • Subscript Assignment

      $ students[0]=Jack$ students[1]=Alex$ students[2]=Amy

      You can also use declare explicit declaration of an array:

      $ declare -a 数组名
    • Direct Assignment

      $ students=(Jack Alex Amy)或$ declare -a studentds=(Jack Alex Amy)
    • Command Assignment
      The output format of the command is as follows

      $ lsDesktop   Downloads  Pictures  Templates  virtualenv  $ arr=($(ls))
    • Dictionary Assignment
      Dictionary can be declare -A declared by command

      $ declare -A dict=([key1]=val1 [key2]=val2)
accessing arrays
创建数组$ students=(Jack Alex Amy)
    • Access by subscript

      $ echo ${students[0]}Jack$ echo ${students[1]}Alex$ echo ${students[2]}Amy
    • List all elements

      $ echo ${students[@]}Jack Alex Amy或$ echo ${students[*]}Jack Alex Amy

      @Both symbols * and symbols can list all elements

Other operations of the array
    • Get array length

      $ echo ${#students[@]}3
    • Print array subscript

      $ echo ${!students[@]}0 1 2

      You can also print the dictionary key value

      $ declare -A dict=([key1]=val1 [key2]=val2)$ echo ${!dict[@]}key2 key1
    • Delete an array

      $ unset 数组名

Introduction to Shell Array usage

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.