Traversal of the shell-array

Source: Internet
Author: User

Multiple values can be stored in an array

The shell array is represented by parentheses, and the elements are separated by a "space" symbol.

Syntax format:

Array_name= (value1 value2 ... valuen)

Defining arrays

Array_name[0]=value0

Array_name[1]=value1

Array_name[2]=value2

Reading an array

${array_name[index]}

my_array= (A B "C" D)

echo "first element: ${my_array[0]}"

echo "second element: ${my_array[1]}"

echo "The third element is: ${my_array[2]}"

echo "fourth element: ${my_array[3]}"

Execute the script with the output as follows:

The first element is: A

The second element is: B

The third element is: C

The fourth element is: D

Get all elements in an array

Use @ or * to get all the elements in the array

For example:

my_array= (A B "C" D)

echo "Elements of array: ${my_array[*]}"

echo "Elements of array: ${my_array[@]}"

Execution results

The elements of the array are: A B C D

The elements of the array are: A B C D

Gets the length of the array

y_array= (A B "C" D)
echo "array element number: ${#my_array [*]}"
echo "array element number: ${#my_array [@]}"

Execution results

Number of array elements: 4

Number of array elements: 4

Loop array

For

[[email protected] ~]# array= (a b C 1 2 3)

[[email protected] ~]# echo ${array[@]}

[[Email protected] ~]# a b c d 1 2 3 4

[Email protected] ~]#

For ((i=0;i<${#array [@]};i++))

Do

Echo ${array[i]}

Done

Execution results

A

B

C

1

2

3

Can also be written as

[[email protected] ~]# for a in ${array[@]}

> Do

> Echo $a

> Done

[email protected] ~]# while [$i-lt ${#array [@]}]

> Do

> Echo ${array[$i]}

> Let i++

> Done

Traversal of the shell-array

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.