14-7 shell脚本进阶数组

一、数组的基本用法

关联数组需要先声明

[root@centos8 ~]#declare -a
declare -a BASH_ARGC=()
declare -a BASH_ARGV=()
declare -a BASH_COMPLETION_VERSINFO=([0]="2" [1]="7")
declare -a BASH_LINENO=()
declare -a BASH_SOURCE=()
declare -ar BASH_VERSINFO=([0]="4" [1]="4" [2]="20" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
declare -a DIRSTACK=()
declare -a FUNCNAME
declare -a GROUPS=()
declare -a PIPESTATUS=([0]="0")
[root@centos8 ~]#declare -a title
[root@centos8 ~]#declare -a 
declare -a title
[root@centos8 ~]#title[0]=ceo
[root@centos8 ~]#title[1]=coo
[root@centos8 ~]#title[2]=cto
[root@centos8 ~]#echo $title[*]
ceo[*]
[root@centos8 ~]#echo ${title[*]}
ceo coo cto
[root@centos8 ~]#car=(bba bmw audi xiaomi)
[root@centos8 ~]#echo${car[2]}
-bash: echoaudi: command not found
[root@centos8 ~]#echo ${car[2]}
audi
[root@centos8 ~]#echo ${car[*]}
bba bmw audi xiaomi
[root@centos8 ~]#ls
10.0.0.136  cmatrix-v2.0-Butterscotch.tar  continue.sh  disk_check.sh  expect3.sh  expect4.sh~  functions         reset.sh
cmatrix     continue2.sh                   dead.letter  expect2.sh     expect4.sh  expect.sh    install_httpd.sh
[root@centos8 ~]#declare -A family   先声明关联数组
[root@centos8 ~]#family[name]=smith
[root@centos8 ~]#family[address]=beijing
[root@centos8 ~]#family[num]=3
[root@centos8 ~]#echo ${family[name]}

[root@centos8 ~]#unset fiamily  删除数组

二、数组切片

[root@centos8 ~]#n=({1..10})
[root@centos8 ~]#echo ${n[*]}
1 2 3 4 5 6 7 8 9 10
[root@centos8 ~]#echo ${n[*]:3}
4 5 6 7 8 9 10
[root@centos8 ~]#echo ${#n[*]:3}
-bash: ${#n[*]:3}: bad substitution
[root@centos8 ~]#echo ${#n[*]}
10
[root@centos8 ~]#n[${#n[*]}]=11
[root@centos8 ~]#echo ${n[*]}
1 2 3 4 5 6 7 8 9 10 11
[root@centos8 ~]#

三、打印杨辉三角

[root@centos8 ~]#cat yanghuisanjiao.sh 
#!/bin/bash
if (test -z $1) ;then
        read -p "请输入行数:" MAX
else
        MAX=$1
fi
for ((i=1;i<=MAX;i++))
do
  for ((j=1;j<=i;j++))
  do
          f=$(($i-1))
         g=$(($j-1))
         if [ "$j" == 1  ];then
            declare SUM_${i}_$j=1
        else
          declare A=$[SUM_${f}_$j]
          declare B=$[SUM_${f}_$g]
          declare SUM_${i}_$j=`expr $A + $B`
        fi
    echo -n $[SUM_${i}_$j]
    echo -en "  "
  done
echo "  "
done

四、随机生成数,并找出最大值和最小值

[root@centos8 ~]#cat max_min.sh 
#!/bin/bash
declare -i min max
declare -a nums
for ((i=0;i<10;i++));do
        nums[$i]=$RANDOM
        [ $i -eq 0  ] && min=${nums[0]} && max=${nums[0]}&& continue
        [ ${nums[$i]} -gt $max  ] && max=${nums[$i]}&& continue
        [ ${nums[$i]} -lt $min  ] && min=${nums[$i]} 
done
echo "All numbers are ${nums[*]}"
echo Max is $max
echo Min is $min

 

posted @ 2023-06-12 11:25  最拉的刺客  阅读(14)  评论(0)    收藏  举报