15-1 shell script Advanced

Advanced shell script

cycle

  • Cycle execution
    • The code segment in a repeat run multiple times
    • How many times repeat run
      • Cycles known in advance
      • Cycles known in advance
    • There are entry conditions and exit criteria
  • for, while, until

for loop

for VAR in [list];do
    CODE
done
  • Implementation mechanisms: in order to list the elements assigned to "variable name"; each assignment after the execution of a loop body; until the elements in the list is exhausted, the end of the cycle
  • List Builder way:
    • (1) directly gives a list of
    • (2) a list of integers:
    • (a) {start..end}
    • (b) $(seq [start [step]] end)
    • (3) returns a list of commands
      • $(COMMAND)
    • (4) the use of glob, such as:. * Sh
    • (5) variable reference
      • $@, $*

for special format

  • Double parentheses methods, i.e., ((...)) format, may also be used for arithmetic operations
  • Double parentheses bash Shell method may also achieve the variable operation C-style
    • I=10
    • ((I++))
  • for circulating special format:
for ((控制变量初始化;条件判断表达式;控制变量的修正表达式))
do
循环体
done
  • Control variables are initialized: the operation is performed only when a loop snippet
  • Correction expression control variables: each cycle ends will carry out correction calculation control variable, and then determines conditions do

while loop

while CONDITION; do  
    循环体  
done
  • CONDITION: loop control conditions; before entering the loop, do first judge; every time to make a judgment before looping again; the condition is "true", then perform a loop; until the condition test status to "false" terminates the loop
  • Thus: CONDTION should generally have a loop control variable; the value of this variable will continue to be fixed in the loop
  • Entry conditions: CONDITION is true
  • Exit condition: CONDITION is false

until loop

until CONDITION; do
    循环体
done
  • Entry conditions: CONDITION is false
  • Exit condition: CONDITION is true

Loop control statements continue

  • A loop body
  • continue [N]: N ahead of the end of the round loop layer, directly to the next round is determined; innermost layer
    a first layer
while CONDTIITON1; do
CMD1
...
if CONDITION2; then
continue
fi
CMDn
...
done

Loop control statements break

  • A loop body
  • break [N]: N layer ahead of the end of the cycle, the innermost layer a first layer
while CONDTIITON1; do
CMD1
...
if CONDITION2; then
break
fi
CMDn
...
done

Loop control shift command

  • shift [n]
  • The parameter list for the specified number of left list, the default is left once.
  • Once the list parameter list is moved, the extreme left of the parameters can be deleted from the list. When the position loop while traversing the list of arguments, used to shift
  • ./doit.sh a b c d e f g h
  • ./shfit.sh a b c d e f g h

while special usage

  • while special usage cycles (each line traversing file)
while read line; do
    循环体
done < /PATH/FROM/SOMEFILE
  • Sequentially reads each line / PATH / FROM / SOMEFILE file, and will be assigned to the variable line row

select the menu cycle

select variable in list 
do 
    循环体命令
done
  • select cycle primarily used to create menus, menu items in numerical order of the standard error will be displayed,
    and displays the PS3 prompt and waits for user input
  • Users enter a number in the menu list, perform the corresponding command
  • User input is stored in the built-in variable REPLY * select an infinite loop, so keep in mind that exit the loop with the break command, or terminated with the exit command
    script. You can also exit the loop press ctrl + c
  • select often used in conjunction with case
  • Similarly for the loop, you can be omitted in list, this time using the position quantity

function

Function Introduction

  • Function is a function statement blocks composed of several pieces of shell commands, programming code reuse and modularity
  • It is similar in form to the shell program, except that it is not a separate process, can not operate independently, but part of the shell program
  • Shell functions and procedures similar, except that
    • Shell runs in the sub-Shell
    • The Shell function runs in the current Shell. Therefore, in the current Shell, the function may be modified shell variables

Defined Functions

  • Function consists of two parts: the function name and the function body * help function
  • A grammar:
f_name (){
...函数体...
} 
  • Grammar II:
function f_name {
...函数体...
} 
  • Grammar III:
function f_name () {
...函数体...
}

Function uses

  • Define and use functions
    • You may be defined function in the interactive environment
    • Can function in a script file as part of its
    • It can be placed in a separate file containing only the function
  • Call: function call will only be executed
    • Call: the name given function
    • Local function name appears, it will be replaced automatically as a function of the code
  • Lifecycle functions: Create is called, terminated return

Function return value

  • There are two function return values:
  • The results of the function's return value:
    1. Use echo commands output
    2. The output of the command to call the function body
  • Function exit status code:
    1. The default depends on the last command executed in the function exit status code
    2. Custom exit status code in the format:
      • return return from the function, the final state determined by command returns the value
      • return 0 No error is returned
      • return 1-255 an error is returned

Interactive environment definition and use functions

  • Example:
dir() {
> ls -l
> }
  • After the definition of the function, if the type $ dir later, the results of which showed the same effect with the ls -l
    • to you
  • The dir function is retained until the user exits from the system, or executing a command as shown below unset
    • unset you

Define and use functions in a script

  • Function must be defined before use, and should therefore be the beginning of a function defined on the script until the shell was first discovered it
    before use
  • Call functions using only the function name to
  • Example:
#!/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”

Use function files

  • Frequently used functions can be stored in the function file and function files loaded shell
  • The file name can be chosen arbitrarily, but better have some connection with the related tasks, such as: functions.main
  • Once the file is loaded function shell, you can call the function at the command line or in scripts. You can use the set command to view all defined functions, the output list includes all the functions already loaded shell
  • To change a function, first with unset command to remove a function from the shell. After the change is completed, and then reload this file

Create a function file

Function File Example:
CAT functions.main

#!/bin/bash
#functions.main
findit()
{
if [ $# -lt 1 ] ; then
echo "Usage:findit file"
return 1
fi
find / -name $1 –print
}

Loading function

  • After the file has been created function, to load it into shell
  • Locate and load the shell function file format
    • . filename 或 source filename
  • Note: namely <Point> <space> <filename>
    • Here filename to take the right path
  • Example:
    • Function in the example above, the following command can be used
    • . functions.main

Check the load function

  • Use the set command to check whether the function is loaded, set command displays all the functions in the shell loaded
  • Example:
set
findit=( ) {
    if [ $# -lt 1 ]; then
        echo "usage :findit file"
        return 1
    fi
    find / -name $1 -print
}
…

Executing shell function

  • To perform a function, you can simply type the name of the function
  • Example:
findit groups
/usr/bin/groups
/usr/local/backups/groups.bak

Delete shell functions

  • After the function now make some changes, you need to delete function, making it unavailable to the shell. Use the unset command to complete the deletion function
  • The command format is:
unset function_name

Example:

unset findit

Then type the command set, the function will no longer be displayed

Environmental function: the child process can also be used

  • Disclaimer: export -f function_name
  • View: export -f or declare -xf

Function Arguments

  • Functions can accept parameters:
    • Parameters passed to the function: the function is called, a given space-separated list of parameters to the function name;
      • For example, "testfunc arg1 arg2 ..."
    • In the body of the function which may be used $ 1, $ 2, ... call parameters; may also be used $ @ $ * $ # and other special variables

Function variables

  • Variable scope:
    • Environment variables: the current shell sub-shell and effective
    • Local variables: effective only in the current shell process, the script will start to implement the dedicated sub-shell process; therefore, local variable scope of the current shell script files, including script function
    • Local variables: life cycle functions; the end of the function variables are automatically destroyed
  • Note: If the function has a local variable, if their names with local variables, use local variables
  • Define local variables in the function Method
    • local NAME=VALUE

Recursive function examples

  • Recursive function:
    • Function calls itself directly or indirectly
    • Note recursive layers
  • Recursion Example:
    • Is the factorial operation symbol Keystone Karman invention in 1808, is a mathematical term, a positive integer factorial (factorial) are all positive integers less than and equal to the product of the number, and there is a 0 factorial, a natural number writing n factorial n!
      • n!=1×2×3×...×n
      • Factorial also be defined recursively:! 0 = 1, n = (n-1) × n!!
      • n!=n(n-1)(n-2)...1
      • n(n-1)! = n(n-1)(n-2)!
  • Example: 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 bomb

  • fork bomb is a malicious program, its interior is a constant in an infinite loop fork process, in essence, a simple recursive program. Since the program is recursive, if there are no restrictions, which can lead to rapid depletion of this simple procedure all the resources inside the system
  • Function to achieve
:(){ :|:& };:
bomb() { bomb | bomb & }; bomb
  • Script to achieve
    • cat Bomb.sh
    • !/bin/bash

    • ./$0|./$0&

Guess you like

Origin www.cnblogs.com/kjalbert/p/11759971.html