Shell basic Syntax (iii)

Source: Internet
Author: User

For statement

Basic format:

For variable name in condition; Do ...; Done


Example: Traversing a directory or file

#!/bin/bashcd/etc/# #脚本中如果查询的目录在多级目录下, first go to the directory, or directly with the absolute path for a in ' ls/etc/' # #遍历目录do if [-D $a ] # #一个一个的去判断是否为目录 then ls-d $a # #如果是目录, view the files and subdirectories in the directory below Fidone


While statement

Basic format:

While condition;

Do ...;

Done


Example: real-time monitoring of load-sending messages

#!/bin/bashwhile: # #: Represents the perpetual loop, and true one meaning do load= ' w|head-1|awk-f ' load average: ' {print $} ' |cut-d.-f1 ' If [ $load-gt]then top|mail-s "Load is High: $load" [email protected] # #这里也可以执行python发邮件的脚本fisleep 30done


Break

Jump out of the loop and execute the instructions after the loop code.


Continue

Skip this cycle and proceed to the next cycle.


Exit

Exits the entire script.


Function

Basic format:

function Fun () {# #定义函数

......

}

Fun 1 2 3 # #传入参数, call function


Variable meaning:

$: First parameter

$ A: The second parameter

$ A: The third parameter

$ A: The name of the script itself

$#: Number of parameters passed in

[Email protected]: all parameters


Sample: View network card IP address

#!/bin/baship () {ifconfig | grep-a1 "$e" |tail-1 | awk ' {print $} '}read-p "Please input the ETH name:" emyip= ' IP $e ' E Cho "$e address is $myip"


Array

Defined:

# a= (1 2 3) # #定义一个数组a并赋值 1 2 3# echo ${a[*]} # #注意输出a的值的格式1 2 3# Echo ${a[1]} # #输出单个a数组中的值2 # echo ${a[ 2]}3# echo ${a[0]} # #注意第一个其实是 01# echo ${#a [@]} # #获取数组的元素个数3

Change:

# a[3]=a # #给第三个数组赋值一个a # echo ${a[*]}1 2 3 a# a[3]=aaa # #修改赋值为aaa # echo ${a[*]}1 2 3 Aaa#echo ${A[@]/5/ASD} # #替换1 2 3 4 ASD 6 7 8

Delete:

# unset A[2] # #删除a数组中第2位的值 # unset a # #删除a数组

Sharding:

# a= (' seq 1 8 ') # #给a赋值8个数 # echo ${a[*]}1 2 3 4 5 6 7 8# Echo ${a[@]:3:3} # #从第3个数组开始, intercept 3. 4 5 6# Echo ${a[@]:0-3:2} # #从倒数第三个开始, fetch two numbers 6 7

Shell basic Syntax (iii)

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.