当前位置:网站首页>Shell arrays and functions

Shell arrays and functions

2022-06-12 19:14:00 benziwu

Catalog

One 、 Concept

Two 、 Normal array

        1-1 Define an array

        1-2 Call array method 1

         Accessing array elements

3、 ... and 、 Associative array

Four 、 Arrays and loops

5、 ... and 、 function

6、 ... and 、 Function arguments

7、 ... and 、 influence Shell The program's built-in commands

Case test

Shift


One 、 Concept

 

Two 、 Normal array

        1-1 Define an array

                array1[1]=appele
[[email protected] ~]# array1[2]=orange
[[email protected] ~]# array1[3]=peach
 array2=(tom jack alice)

# Assign each line of the file to array3
[[email protected] ~]# array3=('cat /etc/passwd')

[[email protected] ~]# array4=('ls /var/ftp/Shell/for*')

[[email protected] ~]# array5=(tom jcak clice "bash shell")

[[email protected] ~]# colors=($red $blue $green $recolor)

[[email protected] ~]# array6=(1 2 3 4 5 6 7 "linux shell" [20]=saltstack) 

        1-2 Call array method 1

[[email protected] ~]# echo ${array1[*]}
pear appele orange peach
[[email protected] ~]# declare -a | grep array1 
declare -a array1='([0]="pear" [1]="appele" [2]="orange" [3]="peach")'
[[email protected] ~]# echo ${array1[@]}
pear appele orange peach

         Accessing array elements

 Accessing array elements :
# echo ${array1[0]}  Access the first element in the array 
# echo ${array1[@]}  Access all the elements in the array   Equate to  echo ${array1[*]}
# echo ${#array1[@]}  Count the number of array elements 
# echo ${!array2[@]}  Get the index of the array element 
# echo ${array1[@]:1}  Index from the array 1 Start 
# echo ${array1[@]:1:2}  Index from the array 1 Start , Access two elements 

3、 ... and 、 Associative array

         Array name [  Indexes ]= A variable's value

         Associative arrays must be defined first and then assigned

        assignment : Assign one value at a time

[[email protected] ~]# declare -A ass_array1   #declare -A  Declare keywords 
[[email protected] ~]# ass_array1[index]=pear
[[email protected] ~]# ass_array1[index1]=apple
[[email protected] ~]# ass_array1[index2]=orange
[[email protected] ~]# ass_array1[index3]=orange
[[email protected] ~]# ass_array1[index3]=peach


 see 
[[email protected] ~]# echo ${ass_array1[*]}
apple orange peach pear

        assignment : Multiple values at a time

declare -A ass_array2
[[email protected] ~]# ass_array2=([index1]=tom [index2]=jack [index3]=alice [index4]="bash shell")

[[email protected] ~]# echo ${ass_array2[index2]}
jack

[[email protected] ~]# echo ${ass_array2[@]}
bash shell tom jack alice

[[email protected] ~]# echo ${#ass_array2[@]}
4
[[email protected] ~]# echo ${!ass_array2[@]}
index4 index1 index2 index3
[[email protected] ~]# 

Four 、 Arrays and loops

        Case study 1:while Scripts quickly define arrays

#!/bin/bash

# Loop read file , Define an array 

while read line
do
        passwd[++i]=$line
done < /etc/passwd
        
        for i in ${!passwd[*]}
        do
                echo "passwd Index of array $i  An array is ,${passwd[$i]}"
        sleep 1 
done        

        Case study 2: for Scripts quickly define arrays

#!/bin/bash

# Define an array 
OLD_IFS=$IFS
IFS=$'\n'
for i in `cat /etc/hosts`
do
hosts[++i]=$i
done

for b in ${!hosts[*]}
do
        echo "hosts  The index of the array is $bb , The value is  ${hosts[$b]}"
done

IFS=$OLD_IFS

#!/bin/bash
# Array statistics gender 
declare -A sex  # Declare an associative array sex
#while  Read the file by line ,for Read by space 
        while read line
        do
type=`echo $line | awk '{print $2}'` #awk   A cutting charm , Cut the specified output 

        let sex[$type]++                # One cycle per household sex  Same sex +1;
        done <sex.txt  # Give each line of file to line

        for i in ${!sex[@]}
        do
                echo "$i,${sex[$i]} "
        done

5、 ... and 、 function

A function is a snippet of code that performs a specific function ( block ) stay shell Function is defined in , You can modularize the code , Easy to reuse code          Note that functions must be defined before they can be used .

        5-1 Defined function 1:            

 Function name () {
     Function to achieve the function code 
        }

        5-2 Defined function 2:

function  Function name {
     Function to achieve the function code 
}

        5-3 Call function      

 Function name 
     Function name   Parameters 1  Parameters 2
 read -p "Input choice:" choice
                case $choice in
                        d)  
        echo "===========dish info============="
                        df -hT
                        ;;    
           
                        m)
        echo "===========meme info============="
                        free -m
                        ;;

                        c)

6、 ... and 、 Function arguments

Case study 1

Let the function define itself   and     Parameters are passed externally

#!/bin/bash
#jiecheng1.ch

fun1(){
factorial=1
for((i=1;i<=$1;++i))
do
#echo "$i"
factorial=$[$factorial*$i]
done
type=$[i-1]
echo “$type The factorial is :$factorial”
}

fun1 1
fun1 2
fun1 3

 perhaps ——————————————————————————————————————————————————————————————————————————————————————

fun1 $1
fun1 $2
fun1 $3

[[email protected] ~]# bash jiecheng1.sh  3 5 10
“3 The factorial is :6”
“5 The factorial is :120”
“10 The factorial is :3628800”

Case study 2  Function arguments Array parameters

Make a simple factorial script , Pass arguments to a function through an array

#!/bin/bash
#NUM_array.sh

num=(1 2 3 4)

array(){
        fac=1
for i in $*
do
fac=$[$fac*$i]
done
        echo $fac
}

array ${num[*]}


***************************************************************************

#!/bin/bash
#NUM_array.sh
num=(1 2 3 4)

array(){
#local Defining variables is only valid in functions 
local j
#fac=1
for i in $*
do

# Define different values *5, Note that the index is used when retrieving values 
outarray[j++]=$[$i+5]
done
        echo "${outarray[*]}"
}

array ${num[*]}

7、 ... and 、 influence Shell The program's built-in commands

 

          Case test

#!/bin/bash

        for i in {A..D}
        do
                echo -n  $i     #echo  Default output line breaks   Use -n  No output 

                for j in {1..9}
                do
                        if [ $j -eq 5 ];then

10                       continue   # Jump out of this cycle ######*****
                        
fi
                        echo -n  $j     #
                done
                        # External circulation is intermittent 
                echo
        done
———————————————————————————————————————————————————————————————————————————
[[email protected] ~]# bash xunhuan.sh
A12346789         Jump out of =5 The cycle of 、 Jump out of the inner loop 
B12346789
C12346789
D12346789          
 10                         break    # interrupt =5 The inner circle of 
——————————————————————————————————————————————————————

[[email protected] ~]# bash xunhuan.sh
A1234
B1234
C1234
D1234
10                         break  2  # interrupt 2 Layer cycle , Inner loop =5 interrupt 
——————————————————————————————————————————————————————————————
bash xunhuan.sh
A1234

Shift

 

#!/bin/bash

while [ $# -ne 0 ]
do
        let sum+=$1
        shift
#       echo #sum 
done
echo "sum:$sum"
————————————————————————————————————————————————————————————————————
[[email protected] ~]# bash sum.sh 1 2
sum : 3

shift 1  Make parameters      Move left 1 position ,shift 2  Make parameters   Move left 2 position 

        summary : Use while Pass the participants into an infinite cycle   Loop in reference shift Equivalent to limiting the number of cycles   

原网站

版权声明
本文为[benziwu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121903425533.html