Array Learning of Bash scripts

Source: Internet
Author: User
Tags array length

indexed arrays and associative arrays can be used in bash, and bash adds support for associative arrays after version 4.0

First, an indexed array

1. Defining an indexed array

# Way 1array_value= (1 2 3 4 5 6)
Or
Array_value= (1, 2, 3, 4, 5, 6) # way 2array_value[0]= ' test1 ' array_value[2]= ' test2 ' ... array_value[5]= ' test6 '

As with other scripting languages, the starting position of an indexed array in bash starts at 0

2. Print an array of items

echo ${array_value[0]} or Index=5echo ${array_value[$index]}

The printing results are as follows:

3. Print all values of the array

echo ${array_value[*]} or echo ${array_value[@]}

The printing results are as follows:

4. Print array length

echo ${#array_value [*]} or echo ${#array_value [@]} Note the difference between the length of the printed array and the length of the string if the echo ${#array_value} is used to obtain a result of 1, it is not the correct result

The printing results are as follows:

Error mode:

Second, associative array

1. Defining Associative arrays

# define associative array assoc_arraydeclare-a Assoc_array

2. Inserting elements

assoc_array= ([Index1]=val1 [Index2]=val2] or Assoc_array[index1]=val1assoc_array[index2]=val2

For example:

3. List the array index

echo ${!assoc_array[*]} or Echo ${!assoc_array[@]} This method also applies to indexed arrays

The results are as follows:

Array Learning of Bash scripts

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.