Simple array usage and examples in shell programming

Source: Internet
Author: User

Origin: in the shell programming teaching conducted by old boys in Linux training, many well-experienced netizens and students are still confused about arrays. The following is a small example of array usage, hope to help you. In fact, the shell array is very simple and easy to use. We should all follow the simple and easy-to-use principle in learning.

Simple array usage and examples in shell programming

The new version of bash supports one-dimensional array. array elements can be initialized using the symbol variable [xx]. In addition, the script can use the declare-a variable statement to specify an array. To reference an array element (that is, the value), you can use braces to access $ {Variable [XX]}. Of course, the following are some frequently used methods and a little understanding of arrays by old boys. If you have a high opinion, thank you for your guidance.

1.1 common definition methods of shell Arrays:
1) Method 1:
Command method:
Dir = ($ (LS .))

Example 1: manual command line operation demonstration
[Root @ oldboy Scripts] # dir = ($ (LS .))
[Root @ oldboy Scripts] # ls.
Oldboy. Log apachemon. Sh httpdctl

[Root @ oldboy Scripts] # echo $ {# dir [*]} <= view the length of the array
3

Command Line print array elements cyclically:
Statement 1:
For (I = 0;I <'echo $ {# dir [*]} ';I ++ ))
Do
Echo-e "$ {dir [$ I]} \ n"
Done
Tip: I <'echo $ {# dir [*]} 'can be replaced with I <$ {# dir [*]} in a simpler way (thanks to yongye brother ).
==========================================
Statement 2:
For (I = 0;I <$ {# dir [*]};I ++ ))
Do
Echo-e "$ {dir [$ I]} \ n"
Done
==========================================
Statement 3:
For (I = 0; I <$ {# Dir [@]};I ++ ))
Do
Echo $ {dir [$ {I}]}
Done

Example 2: define and output array elements through scripts:
[Root @ oldboy Scripts] # Cat printarray. Sh
Dir = ($ (LS .))
For (I = 0;I <$ {# dir [*]};I ++ ))
Do
Echo-e "$ {dir [$ I]} \ n"
Done

[Root @ oldboy Scripts] # sh printarray. Sh
Oldboy. Log

Apachemon. Sh

Httpdctl

Printarray. Sh
========================================================== ================
2) Method 2: List Elements
Array = (red green blue yellow magenta)
Array = (
Oldboy
Zhangyue
Zhangyang
)
Example 3: List script examples of the Element Method
[Root @ oldboy ~ # Cat test. Sh
Array = (
Oldboy
Zhangyue
Zhangyang
)

For (I = 0; I <$ {# array [*]}; I ++ ))
Do
Echo "$ {array [$ I]}"
Done
Echo ----------------------
Echo "array Len :$ {# array [*]}"
[Root @ oldboy ~ # Sh test. Sh
Oldboy
Zhangyue
Zhangyang
Array Len: 3

3) method 3: In fact, method 3 is the same as method 1, which is listed separately for its practical value.
Judge = ($ (curl-I-s $ {url_list [$ I]} | head-1 | TR "\ r" "\ n "))

Example 4: professional production scripts for URL check (shell array method ):
[Root @ oldboy ~] # Cat check_url.sh
#! /Bin/bash
# This script is created by oldboy.
# E_mail: 31333741@qq.com
# QQ info: 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 this 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 200 OK
Judge = ($ (curl-I-s $ {url_list [$ I]} | head-1 | TR "\ r" "\ n "))
If [["$ {Judge [1]}" = '000000' & "$ {Judge [2]}" = 'OK']
Then
Action "$ {url_list [$ I]}"/bin/true
Else
Action "$ {url_list [$ I]}"/bin/false
Fi
Done
}
Check_url
[Root @ oldboy ~] # Sh check_url.sh
3 seconds later, execute this operation ....
Check URL...
Http://etiantian.org [OK]
Http://www.linuxpeixun.com [OK]
Http://oldboy.blog.51cto.com [OK]
Tip: the above results are colored.

Example 5: Implement LVS Server Load balancer health check and automatic removal and automatically add Rs scripts (scripts many years ago)[Root @ oldboy sbin] # Cat health_check_url.sh #! /Bin/bash # This script is created by oldboy. # e_mail: 31333741@qq.com # qqinfo: 31333741 # function: # version: 1.1 Port = "80" VIP = 192.168.1.181rip = (192.168.1.178192.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]}" = '000000' & "$ {Judge [2]}" = 'OK'] thenif ['mongosadm- l-N | grep "$ {rip [$ I]}" | WC-L '-ne 1] then1_sadm-a-t $ VIP: $ port-r $ {rip [$ I]}: $ portfielseif ['prop SADM-l-N | grep "$ {rip [$ I]}" | WC-l'-EQ 1] then1_sadm-D-T $ VIP: $ port-r $ {rip [$ I]}: $ port1_idone} while truedocheck_urlsleep 5 Done

---------------------------------------------------------
1.2 small examples of exercises after reading the blog
Question 1: Save the numbers 1-3 to the array multiplied by 8 and output them in sequence.
Answer:
The following comments have the correct answer. If you are interested, you can first think about writing and then read the comments. If you have any questions, you are welcome to comment and ask questions. If you can, the old boy is willing to answer questions for you.

Question 2: A shell script: The oldboy. SH Content defines an array = (1 2 3)
Number of array elements to print.
Requirement: Use the array as a variable to pass parameters to the script when executing the script (this is the difficulty of this question)
For example, execute sh oldboy. Sh array.
Answer:
The following comments have the correct answer. If you are interested, you can first think about writing and then read the comments. If you have any questions, you are welcome to comment and ask questions. If you can, the old boy is willing to answer questions for you.

For more information about arrays, refer:
Http://www.etiantian.org/ebooks/cn_shell_abs/html/arrays.html

This article is from the "old boy's Linux blog" blog, please be sure to keep this source http://oldboy.blog.51cto.com/2561410/1055734

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.