Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

SHELL script advance

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

For cycle

For variable name in list; do

   cycle body

Done

Executive mechanism

Assign the elements in the list to the variable name in turn; execute the loop body after each assignment; until the elements in the list are exhausted and the loop ends

For special format

The double parenthesis method, that is, ((…)) Format, which can also be used for arithmetic operations

The double parenthesis method can also enable bash Shell to implement C-style variable manipulation.

ITunes 10

((IPCC +))

Special format of for Loop

For ((control variable initialization; conditional judgment expression; modified expression of control variable))

Do

   cycle body

Done

Control variable initialization: execute the modified expression of the control variable only once when running to the loop code segment: at the end of each cycle, the control variable correction operation is performed first, and then the conditional judgment while loop is made.

While CONDITION; do

   cycle body

Done

CONDITION: loop control condition; make a judgment before entering the loop; judge again after each loop; execute a loop if the condition is "true"; until the condition test state is "false" to terminate the loop so: CONDTION should generally have loop control variables The value of this variable is constantly modified in the body of the loop: CONDITION is the true exit condition: CONDITION is the special use of the falsewhile loop (traversing every line of the file)

While read line; do

   cycle body

Done

< /PATH/FROM/SOMEFILE 依次读取/PATH/FROM/SOMEFILE文件中的每一行,且将行赋值给变量line until循环 until CONDITION; do   循环体 done 进入条件: CONDITION 为false退出条件: CONDITION 为true循环控制语句break 用于循环体中 提前结束循环,最内层为第一层continue 用于循环体中 提前结束循环,直接进入下一轮判断;最内层位第1层shift 用于将参量列表 list 左移指定次数,缺省为左移一次 参量列表 list 一旦被移动,最左端的那个参数就从列表中删除。 while 循环遍历位置参量列表时,常用到 shift无限循环 while true; do   循环体 done until false; do   循环体 done select循环与菜单 select variable in list do   循环体命令 done select 循环主要用于创建菜单,按数字顺序排列的菜单项将显示在标准错,并显示 PS3 提示符,等待用户输入 用户输入菜单列表中的某个数字,执行相应的命令 用户输入被保存在内置变量 REPLY 中 select 是个无限循环,因此要记住用 break 命令退出循环,或用 exit 命令终止脚本。也可以按 ctrl+c 退出循环 select 经常和 case 联合使用 与 for 循环类似,可以省略 in list,此时使用位置参量函数 函数function是由若干条shell命令组成的语句块,实现代码重用和模块化编程 它与shell程序形式上是相似的,不同的是它不是一个单独的进程,不能独立运行,而是shell程序的一部分 函数和shell程序比较相似,区别在于 Shell程序在子Shell中运行 而Shell函数在当前Shell中运行。因此在当前Shell中,函数可以对shell中变量进行修改 函数的定义 函数由两部分组成:函数名和函数体 语法一:   f_name (){     ...函数体...   } 语法二:   function f_name {     ...函数体...   } 语法三:   function f_name () {     ...函数体...   } 函数使用函数的定义和使用:   可在交互式环境下定义函数   可将函数放在脚本文件中作为它的一部分   可放在只包含函数的单独文件中调用:函数只有被调用才会执行   调用:给定函数名   函数名出现的地方,会被自动替换为函数代码函数的生命周期:被调用时创建,返回时终止函数返回值 函数有两种返回值: 1、函数的执行结果返回值:   (1) 使用echo等命令进行输出   (2) 函数体中调用命令的输出结果 2、函数的退出状态码:   (1) 默认取决于函数中执行的最后一条命令的退出状态码   (2) 自定义退出状态码,其格式为:   return 从函数中返回,用最后状态命令决定返回值   return 0 无错误返回   return 1-255 有错误返回 在脚本中定义和使用函数 函数在使用前必须定义,因此应将函数定义放在脚本开始部分,直至shell首次发现它后才能使用 调用函数仅使用其函数名即可 示例:   cat func1   #!/bin/bash   # func1   hello()   {     echo "Hello there today's date is date +%F"   }   echo "now going to the function hello"   hello   echo "back from the function" 使用函数文件可以将经常使用的函数存入函数文件,然后将函数文件载入shell文件名可任意选取,但最好与相关任务有某种联系。例如:functions.main一旦函数文件载入shell,就可以在命令行或脚本中调用函数。可以使用set命令查看所有定义的函数,其输出列表包括已经载入shell的所有函数若要改动函数,首先用unset命令从shell中删除函数。改动完毕后,再重新载入此文件创建函数文件 函数文件示例:   cat functions.main   #!/bin/bash   #functions.main   findit()   {     if [ $# -lt 1 ] ; then      echo "Usage:findit file"      return 1     fi     find / -name $1 -print   } 载入函数函数文件已创建好后,要将它载入shell定位函数文件并载入shell的格式   . filename 或 source filename注意:此即 这里的文件名要带正确路径示例:   上例中的函数,可使用如下命令   . functions.main检查载入函数 使用set命令检查函数是否已载入。 set命令将在shell中显示所有的载入函数 示例:   set   findit=( )   {     if [ $# -lt 1 ]; then     echo "usage :findit file";     return 1     fi     find / -name $1 -print   }   … 执行shell函数 要执行函数,简单地键入函数名即可 示例:   findit groups   /usr/bin/groups   /usr/local/backups/groups.bak 删除shell函数 现在对函数做一些改动后,需要先删除函数,使其对shell不可用。使用unset命令完成删除函数 命令格式为:   unset function_name 示例:   unset findit   再键入set命令,函数将不再显示 环境函数 使子进程也可使用   声明:export -f function_name   查看:export -f 或 declare -xf 函数参数 函数可以接受参数:    传递参数给函数:调用函数时,在函数名后面以空白分隔给定参数列表即可; 例如"testfunc arg1 arg2 ..."   在函数体中当中,可使用$1, $2, ...调用这些参数;还可以使用$@, $*, $#等特殊变量 函数变量变量作用域:    环境变量:当前shell和子shell有效    本地变量:只在当前shell进程有效,为执行脚本会启动专用子shell进程;因此,本地变量的作用范围是当前shell脚本程序文件,包括脚本中的函数    局部变量:函数的生命周期;函数结束时变量被自动销毁注意:如果函数中有局部变量,如果其名称同本地变量,使用局部变量在函数中定义局部变量的方法    local NAME=VALUE函数递归 函数直接或间接调用自身 注意递归层数 示例:fact.sh   #!/bin/bash   fact() {    if [ $1 -eq 0 -o $1 -eq 1 ]; then      echo 1    else      echo $[$1*$(fact $[$1-1])]    fi   }   fact $1 fork进程 fork进程是一种恶意程序,它的内部是一个不断在fork进程的无限循环,实质是一个简单的递归程序。由于程序是递归的,如果没有任何限制,这会导致这个简单的程序迅速耗尽系统里面的所有资源 函数实现   :(){ :|:& };:   bomb() { bomb | bomb & }; bomb 脚本实现   cat Bomb.sh   #!/bin/bash   ./$0|./$0& 信号捕捉trap trap '触发指令' 信号    进程收到系统发出的指定信号后,将执行自定义指令,而不会执行原操作 trap '' 信号    忽略信号的操作 trap '-' 信号    恢复原信号的操作 trap -p    列出自定义信号操作 trap finish EXIT    当脚本退出时,执行finish函数 数组变量:存储单个元素的内存空间数组:存储多个元素的连续的内存空间,相当于多个变量的集合数组名和索引   索引:编号从0开始,属于数值索引   注意:索引可支持使用自定义的格式,而不仅是数值格式,即为关联索引,bash5.0版本之后开始支持   bash的数组支持稀疏格式(索引不连续)声明数组:   declare -a ARRAY_NAME   declare -A ARRAY_NAME 关联数组   注意:两者不可相互转换数组赋值数组元素的赋值   (1) 一次只赋值一个元素     ARRAY_NAME[INDEX]=VALUE     weekdays[0]="Sunday"     weekdays[4]="Thursday"   (2) 一次赋值全部元素     ARRAY_NAME=("VAL1" "VAL2" "VAL3" ...)   (3) 只赋值特定元素     ARRAY_NAME=([0]="VAL1" [3]="VAL2" ...)   (4) 交互式数组值对赋值     read -a ARRAY显示所有数组 declare -a 引用数组引用数组元素   ${ARRAY_NAME[INDEX]}   注意:省略[INDEX]表示引用下标为0的元素引用数组所有元素   ${ARRAY_NAME[]}   ${ARRAY_NAME[@]}数组的长度(数组中元素的个数)   ${#ARRAY_NAME[]}   ${#ARRAY_NAME[@]}删除数组中的某元素:导致稀疏格式   unset ARRAY[INDEX]删除整个数组   unset ARRAY数组数据处理引用数组中的元素:  数组切片:     ${ARRAY[@]:offset:number}br/>

   array slices:

     ${ARRAY [@]: offset:number}

Number of elements to be taken out by   number

All elements after      takes the offset

     ${ARRAY [@]: offset} appends elements to the array:

   ARRAY [${# ARRAY [*]}] = value associative array:

   declare-An ARRAY_NAME

   ARRAY_NAME= ([idx_name1] = 'val1' [idx_name2] =' val2'...)

   Note: associative array must be declared before calling string slice ${# var}: return the length of the string variable var ${var:offset}: return the string variable var starting with the character after the offset (excluding the offset). In the last part, the value of offset is between 0 and ${# var}-1 (after bash5.2) Negative value allowed) ${var:offset:number}: returns the string variable var starting from the character after the offset (excluding the offset), and the length of the number part ${var:-length}: take the rightmost characters of the string

   Note: there must be a blank character ${var:offset:-length} after the colon: skip the offset character from the far left and take it right to the content before the rightmost lengh character ${var:-length:-offset}: start with the length character from the rightmost left, and then get the content between the rightmost offset characters.

   Note:-length pre-space string processing is based on pattern fetch substring

   ${var#word}: where word can be any character specified

   function: from left to right, find the word in the string stored in the var variable for the first time, and delete all characters between the beginning of the string and the first occurrence of the word string (including)

   ${var##word}: same as above, greedy mode, except that everything between the beginning of the string and the last character specified by word is deleted:

   file= "var/log/messages"

   ${file#/}: log/messages

   ${file##/}: messages$ {var%word}: where word can be any character specified

   function: from right to left, find the word that appears for the first time in the string stored in the var variable, and delete all characters between the last character of the string to the left to the first occurrence of the word string (including)

   file= "/ var/log/messages"

   ${file%/}: / var/log$ {var%%word*}: same as above, except that all characters between the rightmost character of the string and the last occurrence of the word character are deleted:

   url= http://www.magedu.com:80

   ${url##:} 80

   ${url%%:} http find and replace

   ${var/pattern/substr}: find the string represented by var that is matched by pattern for the first time and replace it with substr

   ${var//pattern/substr}: find all strings that can be matched by pattern in the string represented by var and replace it with substr

   ${var/#pattern/substr}: find the string represented by var to which the beginning of the line is matched by pattern, and replace it with substr

   ${var/%pattern/substr}: find the string represented by var to which the end of the line is matched by pattern, and replace it with substr to find and delete it.

   ${var/pattern}: delete the string represented by var that is matched by pattern for the first time

   ${var//pattern}: delete all strings that are matched by pattern in the string represented by var

   ${var/#pattern}: delete all strings in the string represented by var that are matched with pattern as the beginning of the line

   ${var/%pattern}: removes all string character case conversion matched with pattern at the end of the line in the string represented by var

   ${var^ ^}: converts all lowercase letters in var to uppercase

   ${var,}: converts all uppercase letters in var to lowercase variable assignments

Advanced variable usage-typed variables Shell variables are generally untyped, but bash Shell provides declare and typeset commands to specify the type of variable, and the two commands are equivalent declare [option] variable names

  -r declares or displays read-only variables

  -I defines a variable as an integer.

  -a defines variables as arrays

  -A defines variables as associative arrays

  -f displays all defined function names and their contents

  -F displays only all defined function names

  -x declares or displays environment variables and functions

  -l declares the variable as the lowercase letter declare-l var=UPPER

  -u declares variables as uppercase letters declare-u var=lowereval command

The eval command will scan the command line for all replacements before executing the command. This command applies to variables that cannot perform its function in a single scan. This command scans variables twice

Example:

   [root@server ~] # CMD=whoami

   [root@server ~] # echo $CMD

   whoami

   [root@server ~] # eval $CMD

   root

   [root@server ~] # nasty 10

   [root@server ~] # echo {0.roomn}

   {0..10}

   [root@server ~] # eval echo {0.roomn}

   0 1 2 3 4 5 6 7 8 9 10

Indirect variable reference if the value of the first variable is the name of the second variable, referencing the value of the second variable from the first variable is called the indirect variable reference variable1. The value of variable2 is the variable name, the value of variable2 is value, and the indirect variable reference refers to the behavior of obtaining the variable value value through variable1.

   variable1=variable2

   variable2=valuebash Shell provides two formats to implement indirect variable references

   eval tempvar=\ $$variable1

   tempvar=$ {! variable1} create temporary files mktemp command: create and display temporary files to avoid conflicts with mktemp [OPTION]. [TEMPLATE]

   TEMPLATE: filenameXXX

     X must have at least three OPTION:

  -d: create a temporary directory

  -p DIR or-- tmpdir=DIR: indicates the location of the directory where temporary files are stored. Example:

   mktemp / tmp/testXXX

   tmpdir=mktemp-d / tmp/testdirXXX

   mktemp-- tmpdir=/testdir testXXXXXXexpectexpect syntax:

   expect [options] [- c cmds] [[- [f | b]] cmdfile] [args]

Option

-c: execute expect scripts from the command line, default expect is executed interactively

     example: expect-c 'expect "\ n" {send "pressed enter\ n"}

-d: you can output debugging information

     example: expect-d ssh.exp

Related commands in expect

   spawn starts a new process

   send is used to send strings to the process

   expect receives strings from the process

   interact allows user interaction

   exp_continue matches multiple strings and adds this command after the action is performed

   set timeout waits for command output time, which defaults to 10 seconds. Once the timeout is reached, and there is still no screen output, the following code in the expect script executes

Expect's most commonly used syntax (tcl language: pattern-Action) single branch pattern syntax:

   expect "hi" {send "You said hi\ n"}

When    matches to hi, it outputs "you said hi" and breaks the line.

Multi-branch pattern syntax:

   expect "hi" {send "You said hi\ n"}\

     "hehe" {send "Hehe yourself\ n"}\

     "bye" {send "Good bye\ n"}

When    matches any string of hi,hello,bye, the corresponding output is executed. The equivalent is as follows:

   expect {

     "hi" {send "You said hi\ n"}

     "hehe" {send "Hehe yourself\ n"}

     "bye" {send "Good bye\ n"}

  }

.

Personal experience

When identifying a string, there must be a space between "and {, otherwise it will not be recognized successfully, remember!

Example

   #! / usr/bin/expect

   spawn scp / etc/fstab 192.168.8.100:/app

   expect {

     "yes/no" {send "yes\ n"; exp_continue}

     "password" {send "magedu\ n"}

  }

   expect eof

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report