shell数组使用

简介:

论坛里的一个兄弟要同时折腾两个变量,不知道如何折腾. 后来了解到可以用数组

都忘记shell还有数组了.


写了一个测试程序. 记录一下. 以后也有个印象.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash
 
declare  -a tmp
 
for  in  $( find  /bin  - type  f)
do
     let  c++
     tmp[c]= "$i"
done
 
len= "${#tmp[@]}"   #array length
 
c=len
for  in  $( find  /usr/bin  - type  f)
do
     let  c++
     tmp[c]= "$i"
done
 
i=0
while  [ $i - le  $len ]
do
     let  i+=1
     echo  "BIN:${tmp[i]}; USR:${tmp[i+len]}"
done
 
bash  a.sh  
BIN: /bin/cp  USR: /usr/bin/semodule_link
BIN: /bin/redhat_lsb_init  USR: /usr/bin/gst-launch
BIN: /bin/readlink  USR: /usr/bin/opgprof
BIN: /bin/unicode_start  USR: /usr/bin/eu-strings
BIN: /bin/ps  USR: /usr/bin/pango-querymodules-64
BIN: /bin/lsblk  USR: /usr/bin/w
BIN: /bin/sleep  USR: /usr/bin/smbta-util
BIN: /bin/setserial  USR: /usr/bin/aserver
BIN: /bin/unicode_stop  USR: /usr/bin/patch
BIN: /bin/cgget  USR: /usr/bin/pdftops
BIN: /bin/nano  USR: /usr/bin/lzmainfo
BIN: /bin/cgdelete  USR: /usr/bin/gstack
BIN: /bin/ln  USR: /usr/bin/rngtest
BIN: /bin/mkdir  USR: /usr/bin/nfs4_setfacl
BIN: /bin/mknod  USR: /usr/bin/vimtutor
BIN: /bin/dumpkeys  USR: /usr/bin/op-check-perfevents
BIN: /bin/ipcalc  USR: /usr/bin/sedispol
BIN: /bin/gzip  USR: /usr/bin/reporter-mailx
BIN: /bin/true  USR: /usr/bin/tiff2pdf
BIN: /bin/mv  USR: /usr/bin/urlgrabber
BIN: /bin/dbus-uuidgen  USR: /usr/bin/groffer
BIN: /bin/cgsnapshot  USR: /usr/bin/smbcquotas
BIN: /bin/env  USR: /usr/bin/nfs4_getfacl
BIN: /bin/arch  USR: /usr/bin/repomanage
BIN: /bin/echo  USR: /usr/bin/eu-unstrip
BIN: /bin/touch  USR: /usr/bin/ . ssh .hmac

脚本取第一次的结果长度为后面while的最大长度.


数组还可以直接  

1
for  in  ${array[@]};  do  ... ;  done

但要同时取两个变量就不好折腾了.


另外数组还有分片, 替换等高级功能, 这个目前没用到. 不写了.


还是折腾python为主...



附, 那边论坛版主的脚本. 使用三目运算等等, 更加简洁

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
 
bin=( $( find  /bin  - type  f) )
ubin=( $( find  /usr/bin  - type  f) )
 
(( len = ${ #bin[@]} < ${#ubin[@]} ? ${#bin[@]} : ${#ubin[@]} ))
 
for  (( i = 0; i < len; i++ ));  do
     echo  "/bin: ${bin[$i]}"
     echo  "/usr/bin: ${ubin[$i]}"
done



本文转自 nonono11 51CTO博客,原文链接:http://blog.51cto.com/abian/1678202,如需转载请自行联系原作者
相关文章
|
5月前
|
Shell 索引
shell脚本入门到实战(四)- 数组
shell脚本入门到实战(四)- 数组
|
8月前
|
Shell 索引
shell编程之数组
shell编程之数组
50 0
|
1月前
|
人工智能 机器人 Shell
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
|
7月前
|
Shell Linux PHP
|
7月前
|
Shell Linux PHP
|
5月前
|
存储 前端开发 JavaScript
shell(七)数组
数组可以存储多个数据,这个东西是很重要的,其他一些高级语言类似PHP、javascript等语言都是支持多维数组的。Shell编程只支持一维数组。 Shell编程的数组和PHP的数组类似,声明的时候不需要指定大小。也可以使用下标来访问数组中的元素。 Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下:
39 0
|
5月前
|
Shell PHP
Shell 数组
Shell 数组
22 0
|
6月前
|
Shell 索引
我们一起来学Shell - shell的数组
我们一起来学Shell - shell的数组
72 0
|
7月前
|
Shell Linux PHP
|
7月前
|
Shell Linux PHP