A tutorial on the operation of Shell script arrays in Linux

Source: Internet
Author: User
Tags array length arrays

Array Assignment: A= (1 2 3 4 5)
A[1]=1

Array length: Echo ${#a [@]}

or echo ${#a [*]}

Read array: Echo ${a[@]}

or Echo ${a[*]}
echo ${a[0]} PS: array subscript starting from 0
Delete array: unset a
Unset A[1]
Array fragmentation: Echo ${a[@]:0:3} displayed as 1,2,3 PS: Intercept the first 3 array values display
Array replacement: Echo ${a[@]/3/100} displayed as 1,2,100,4,5
Array Loop value usage:
For FILE in ${a[@]};d o
Echo ${file};
Done

Display values:

#!/bin/bash
chars= ' ABCDEFGHIJKLMNOPQRSTUVWXYZ '
for ((i=0; i<26; i++)); Todo
array[$i]=${chars: $i: 1}
echo ${array[$i]}
Done

Example Supplements

1. Place a string in an array to get its length

#!/bin/bash
Str= "A B--n D"
Array= ($STR)
length=${#array [@]}
Echo $length

for ((i=0; i< $length; i++))
Todo
echo ${array[$i]}
Done

Execution results:

[Oracle@99bill-as9 array]$ SH length.sh
4
A
B
--n
D

To print a string:

#!/bin/bash
Str= "a b C"
For I in $str
Todo
Echo $i
Done

Or:

#!/bin/bash
Str= "a b C"
Array= ($STR)
For ((i=0;i<${#array [@]};i++))
Todo
echo ${array[$i]}
Done

Execution results:

A
B
C

2. String is split with other characters

#!/bin/bash

Str2= "A#b#c"
A= ($ (echo $str 2 | tr ' # ' | tr-s '))
length=${#a [@]}

for ((i=0; i< $length; i++))
Todo
echo ${a[$i]}
Done
#echo ${a[2]}

Execution results:

A
B
C

3. Other actions for arrays

#!/bin/bash
Str= "A b--n dd"
Array= ($STR)
length=${#array [@]}

The first element of the array is the direct output of #ouput
Echo $array

#Use Subscript Way Access array accesses the elements of an element in a subscript way
Echo ${array[1]}

#Output the array output
Echo ${array[@]}

#Output in the array subscript for 3 the length of the element that is labeled 3 in the output array
Echo ${#array [3]}

#Output in the array subscript 1 to 3 element output array subscript 1 to 3
Echo ${array[@]:1:3}

#Output in the array subscript greater than 2 elements output array lower-than-2 element
Echo ${array[@]:2}

#Output in the array subscript less than 2 elements output array lower than 2 element
Echo ${array[@]::2}

Execution results:

A
B
A b--n DD
2
b--n DD
--n DD
A b

4. Traversal accesses a string (the default is separated by a space and can refer to 2 when the string is separated by another delimiter)

#!/bin/bash
Str= "a--m"
For I in $str
Todo
Echo $i
Done

Execution results:

A
--m

5. How to use Echo to output a string str= "-n". Because-n is an argument to echo, the general method of echo "$str" is not output.
Solutions can include:


echo X$str | Sed ' s/^x//'
Echo-ne "$STR \ n"
Echo-e "$str \n\c"
printf "%s\n" $str (this can also be)


1, from "standard input" read n times string, each input string stored in array


#!/bin/bash
I=0
N=5
While ["$i"-lt $n]; Todo
echo "Please input strings ... ' expr $i + 1 '"
Read array[$i]
b=${array[$i]}
echo "$b"
i= ' expr $i + 1 '
Done
2, put the letters in the string into the array, and output to the "standard output"


#!/bin/bash
chars= ' ABCDEFGHIJKLMNOPQRSTUVWXYZ '
for ((i=0; i<26; i++)); Todo
array[$i]=${chars: $i: 1}
echo ${array[$i]}
Done
What's interesting here is ${chars: $i: 1}, which means to get 1 characters starting from the $i position of the chars string. If you change 1 to 3, you get 3 characters ~ The result is:
Abc
Bcd
...
Vxy
Xyz
YZ//There is not enough string to get the
z//Not enough string to get the
Here are some examples of applying arrays to shell environment variables.

3. Apply the array to the shell environment variable (1)


Array Assignment:
[Root@pps ~]# season= ("srping" "Summer" "Autumn" "Winter")
When you find that the assignment is wrong, you can also immediately correct the new assignment, as Spring above is written as srping.
Re-assignment: (The original value is overridden)
[Root@pps ~]# season= ("Spring" "Summer" "Autumn" "Winter")

Check out the environment variables:
[Root@pps ~]# Set | grep SEASON
season= ([0]= "Spring" [1]= "Summer" [2]= "Autumn" [3]= "Winter")

Display the entire array:
[Root@pps ~]# echo ${season[*]} or echo ${season[@]}
Spring Summer Autumn Winter

To display an array element:
[Root@pps ~]# echo ${season[3]}
Winter

To assign a value to a single array element:
[Root@pps ~]# season[0]= "New_spring"

Look at the array again:
[Root@pps ~]# echo ${season[*]}
New_spring Summer Autumn Winter

Clears the specified single array element:
[Root@pps ~]# unset season[2]

Clear the entire array:
[Root@pps ~]# unset SEASON
4. Apply the array to the shell environment variable (2)
To convert a carriage return in a file to a space using the TR command:


[Root@pps ~]# Cat/etc/shells | TR "\ n" "" ">/tmp/tmp.file

To assign the contents of a file to an array: (before the first return character is encountered)


[Root@pps ~]# read-a SHELLS </tmp/tmp.file

To view array assignments:


[Root@pps ~]# Set | grep "SHELLS"
shells= ([0]= "/bin/sh" [1]= "/bin/bash" [2]=]/sbin/nologin [3]= "/bin/tcsh" [4]= "/bin/csh" [5]= "/bin/ksh"]

This array environment variable can be applied to other shell scripts or applications later.

Extraction of arrays
To start from the tail:

array= ([0]=one [1]=two [2]=three [3]=four]
${ARRAY[@]:1} # Two three four, remove all elements after the first element, then ${array[@]:0} represents all elements
${array[@]:0:2} # One Two
${array[@]:1:2} # Two Three
Sub-string deletion


[Root@localhost dev]# Echo ${array[@]:0}
One two three four
[Root@localhost dev]# Echo ${array[@] #t *e} # Start the shortest match on the left: ' T*e ', which will match to ' thre '
One two E four
[Root@localhost dev]# echo ${array[@]# #t *e} # Start the longest match on the left, which will match to ' three '
[Root@localhost dev]# array= ([0]=one [1]=two [2]=three [3]=four]]
[Root@localhost dev]# Echo ${array[@]%o} # Start the shortest match from the end of the string
One TW three Four
[Root@localhost dev]# Echo ${array[@]%%o} # start the longest match from the end of the string
One TW three Four
Child string Substitution

[Root@localhost dev]# array= ([0]=one [1]=two [2]=three [3]=four]]
The first one to be matched will be deleted.

[Root@localhost dev]# Echo ${array[@]/o/m}
Mne TWM Three Fmur
All matches will be deleted.

[Root@localhost dev]# Echo ${array[@]//o/m}
Mne TWM Three Fmur
No replacement substring is specified, then a matching substring is deleted

[Root@localhost dev]# Echo ${array[@]//o/}
NE tw three fur
Replacement string Front terminal string

[Root@localhost dev]# Echo ${array[@]/#o/k}
Kne two Three Four
Replacement string Rear terminal string

[Root@localhost dev]# Echo ${array[@]/%o/k}
One TWK three Four

All right, here we go. The array operation on the shell command is summed up here, hoping to help you.

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.