Array usage in shell scripts in Linux

Source: Internet
Author: User
Tags array definition arrays

In the shell (I'm bash here) there is no traditional "data type", and the values stored in any variable are "strings" of characters. Of course, you can declare a variable to be an integral type, an array, and so on by declare. Among them, the array is the article to specifically talk about. In bash, only one-dimensional arrays are supported, and, of course, multidimensional arrays can be emulated in the form of associative arrays (associative array).

1. The Declaration of the array
Declaring an array with the DECLARE-A array is an array, with declare-a A_array declaring that A_array is an associative array.
In the shell, declare declaring an array is not required.

2. Initialization of Array (Assignment)
In the shell, parentheses are used to represent the array, and the array elements are separated by a "space" symbol. The general form of the definition array is: array_name= (Value0, value1, ... valuen)
Each element can also be assigned to a separate value, such as: Array[0]=foo; Array[3]=bar (You can not use consecutive subscript, and the scope of the subscript is not limited)

3. Accessing elements of an array
An array initialized using the Array_name= (Value0, value1, ...) format, with the subscript starting at 0, to access a subscript element in the array using the ${array_name[index]} format.
${array_name[@]} and ${array_name[*]} represent all elements in an array, except that the ${array [@]} Gets an element separated by a space, and the ${array [*]} gets an entire string. (This difference is similar to the $@, $* representing the script's parameter list)

4. Length of the array (number of elements) and string length of the element
The length of the array is the number of elements, obtained by ${#array_name [@]} or ${#array_name [*]}, and the string length of one of the elements is ${#array_name [index]}.

5. Truncation of arrays
{Array_name[@]:1} represents all elements except the 1th element (small sign 0)
{Array_name[@]:1:4} represents the 2nd, 3, 4 (subscript 1,2,4-1) Element

6. To cancel an array element or an entire array
Cancels the definition of an array unset array_name
Cancels an element in an array unset Array_name[index]

7. Associative arrays, multidimensional arrays
An associative array can simulate an array of any multidimensional. See Code: HTTPS://GITHUB.COM/SMILEJAY/SHELL/BLOB/MASTER/SH2016/FAKE_TWO_DEMENSINAL_ARRAY.SH

According to a sample shell script described above, run and modify it to help you understand the array in the shell:

#!/bin/bash
#use Array in Bash script
array1= (Alpha Beta Gamma)
echo "array1[0]: ${array1[0]}"
echo "array1[1]: ${array1[1]}"
echo "Len of array1: ${#array1 [@]}"
echo "Len of array1: ${#array1 [*]}"
echo "Len of array1[0]: ${#array1 [0]}"
echo "\${array1[@]}: ${array1[@]}"
echo "\${array1[*]}: ${array1[*]}"
echo "\${array1[@]1}: ${array1[@]:1}"
echo "\${array1[@]1}: ${array1[@]:0:2}"

echo ""
echo "for in \${array1[@]}:"
For i in "${array1[@]}"
Todo
Echo $i
Done
echo ""
echo "for in \${array1[*]}:"
For i in "${array1[*]}"
Todo
Echo $i
Done
echo ""

Unset Array1[0]
echo "\${array1[@]: ${array1[@]}"
echo ""

array2[0]=11
Array2[1]=22
Array2[3]=foo

echo "Array2: ${array2[@]}\n"


ls_out= ($ (ls *.sh))
echo "Len of Ls_out is ${#ls_out [@]}"
For I in $ (SEQ 0 $ (${#ls_out [@]}-1))
Todo
echo "Ls_out[${i}] ${ls_out[$i]}"
Done

Example

Array definition, traversal

Array definition:

Arr= (1 2 3 4 5) # Note is separated by a space, not a comma!!

Array Definition Method 2:

Array
Array[0]= "a"
Array[1]= "B"
Array[2]= "C"

Gets the length of the array (there are several elements in the array):

${#array [@]}


Traversal (For loop method):


For Var in ${arr[@]};
Todo
Echo $var
Done

Traversal (with array subscript):


For i in "${!arr[@]}"; Todo
printf "%s\t%s\n" "$i" "${arr[$i]}"
Done

Traversal (While loop method):


I=0
While [$i-lt ${#array [@]}]
Todo
echo ${array[$i]}
Let i++
Done
To pass an array to a function:

Because the shell is not supported by an array of arrays, this is a relatively troublesome issue.

Read a lot of StackOverflow posts, in addition to global variables, there is no perfect solution.

Here's a workaround, we can convert the array to a string before calling the function.
In the function, read the string and divide it into arrays to achieve the purpose.


Fun () {
        local _arr= (' echo $ | cut-d '  --output-delimiter= ""-F 1-')
        local _n_arr=${#_arr [@]}
         for ((i=0;i<$_n_arr;i++));
        do 
                 elem=${_arr[$i]}
                 echo "$i: $elem"
        done;
}
 
array= (a b c)
Fun "$ (echo ${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.