Easily master the common usage and examples of arrays in shell programming

Source: Internet
Author: User
Tags curl

Origin: In the old boy Linux training shell programming teaching, found a lot of good level of friends and classmates are still very confused, the following for everyone to share the use of the array of small examples, I hope to give you a little help. In fact, the shell array is very simple and useful. We should follow the principles of simplicity and ease of use in our study.

Simple usage and examples of arrays in shell programming

The new version of Bash supports one-dimensional arrays. Array elements can be initialized using the notation variable[xx], and so on. In addition, scripts can use the DECLARE-A variable statement to specify an array, and so on. To refer to an array element (that is, to take a value), you can use braces, access the form ${variable[xx]}, of course, the following are some of the old boys often used methods and a little understanding of the array, if there are ideas, welcome guidance, first thank Bo friends.

1.1 A common way to define shell arrays:
1) Method One:
Order Method:
Dir= ($ (ls.))

Example 1: Manual command line Operation demo
[[email protected] scripts]# dir= ($ (ls.))
[[email protected] scripts]# ls.
Oldboy.log apachemon.sh Httpdctl

[[email protected] scripts]# echo ${#dir [*]} <== View the length of the array
3

The command line loops the print group element:
Notation 1:
for (i=0; i< ' echo ${#dir [*]} '; i++))
Do
Echo-e "${dir[$i]}\n"
Done
Tip:i< ' echo ${#dir [*]} ' can be replaced with a simpler notation i<${#dir [*]} (thanks to the Forever brother).
====================================
Notation 2:
for ((i=0; i<${#dir [*]}; i++))
Do
Echo-e "${dir[$i]}\n"
Done
====================================
Notation 3:
For ((i=0;i<${#dir [@]}; i++))
Do
echo ${dir[${i}]}
Done

Example 2: Defining and outputting array elements through scripting:
[email protected] scripts]# cat printarray.sh
Dir= ($ (ls.))
for ((i=0; i<${#dir [*]}; i++))
Do
Echo-e "${dir[$i]}\n"
Done

[Email protected] scripts]# sh printarray.sh
Oldboy.log

apachemon.sh

Httpdctl

printarray.sh
====================================================
2) Method Two: Enumeration element method
array= (red green blue Yellow magenta)
Array= (
Oldboy
Zhangyue
Zhangyang
)
Example 3: Examples of scripts that enumerate element methods
[email protected] ~# cat test.sh
Array= (
Oldboy
Zhangyue
Zhangyang
)

for ((i=0; i< ${#array [*]}; i++))
Do
echo "${array[$i]}"
Done
Echo----------------------
echo "Array len:${#array [*]}"
[Email protected] ~# sh test.sh
Oldboy
Zhangyue
Zhangyang
Array Len:3

3) Method 3: In fact, method three and method one, because it has a good actual combat value, so separate list of explanations
Judge= ($ (curl-i-S ${url_list[$i]}|head-1|tr "\ r" "\ n"))

Example 4: Compare professional production to check the URL address of the script (Shell array method):
[email protected] ~]# cat check_url.sh
#!/bin/bash
# This script was created by Oldboy.
# E_mail:[email Protected]
# qqinfo:49000448
# Function:check Web URL
# version:1.1
. /etc/init.d/functions

Url_list= (
http://etiantian.org
Http://www.linuxpeixun.com
Http://oldboy.blog.51cto.com
)

function Wait ()
{
Echo-n ' 3 seconds later, perform the operation. ';
For ((i=0;i<3;i++))
Do
Echo-n "."; Sleep 1
Done
Echo
}
function Check_url ()
{
Wait
echo ' Check URL ... '
for ((i=0; i<${#url_list [*]}; i++))
Do
# http/1.1 OK
Judge= ($ (curl-i-S ${url_list[$i]}|head-1|tr "\ r" "\ n"))
if [["${judge[1]}" = = ' && "${judge[2]}" = = ' OK ']
Then
Action "${url_list[$i]}"/bin/true
Else
Action "${url_list[$i]}"/bin/false
Fi
Done
}
Check_url
[Email protected] ~]# sh check_url.sh
After 3 seconds, do the operation ....
Check URL ...
http://etiantian.org [OK]
http://www.linuxpeixun.com [OK]
http://oldboy.blog.51cto.com [OK]
Tip: The above results are color-colored.

Example 5: Implementation of the LVS load Balancing health check and automatic culling and automatic addition of RS scripts (scripts years ago)[[email protected] sbin]# cat health_check_url.sh     #!/bin/bash# This script is Created by oldboy.# e_mail:[email protected]# qqinfo:31333741# function:# version:1.1port= "Up" VIP= 192.168.1.181rip= (    192.168.1.178    192.168.1.179) function Check_url () {for (i=0; i< ${#RIP [*]}; i++)) dojudge= ($ (curl-i-S http://${rip[$i]}|head-1|tr "\ r" "\ n")) if [["${judge[1]}" = = ' "&&" ${judge[2]} "= = ' OK ']]   then     if [' ipvsadm-l-n|grep ' ${rip[$i]} "|wc-l '-ne 1]   &nb sp;  then      ipvsadm-a-T $VIP: $PORT-R ${rip[$i]}: $PORT      fi& nbsp;else      if [' ipvsadm-l-n|grep ' ${rip[$i]} "|wc-l '-eq 1]    & nbsp then      ipvsadm-d-T $VIP: $PORT-R ${rip[$i]}: $PORT        Fifidone} while Truedo check_url sleep 5donE

---------------------------------------------------------
1.2 Small examples that you can practice after reading a blog post
Question 1: Multiply the 1-3 3 numbers into the array by 8 and then output them sequentially.
Answer:
The following comments have the correct answer, interested friends can first think about writing, and then read the comments, if there are questions to welcome comments to ask questions, if possible old boy willing to answer doubts for you.

Issue 2: A shell script: oldboy.sh content defines an array array= (1 2 3)
The number of elements of the group to be printed.
Requirements: To use the array as a variable in the execution script Shishun to the script (this is the difficulty of the subject)
For example: This executes the sh oldboy.sh array
Answer:
The following comments have the correct answer, interested friends can first think about writing, and then read the comments, if there are questions to welcome comments to ask questions, if possible old boy willing to answer doubts for you.

More knowledge of the group, we can refer to:
Http://www.etiantian.org/ebooks/cn_shell_abs/html/arrays.html

This article is from the "Old Boys Linux Training" blog, make sure to keep this source http://oldboy.blog.51cto.com/2561410/1055734

Easily master the common usage and examples of arrays in shell programming

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.