• linux之shell脚本练习


    以下脚本已经是在ubuntu下测试的

    demo持续更新中。。。

    1、for 循环测试,,,Ping 局域网

    1. #!/bin/bash
    2. i=1
    3. for i in {1..254}
    4. do
    5. # 每隔0.3s Ping 一次,每次超时时间3s,Ping的结果直接废弃
    6. ping-w 3 -i 0.3 192.168.110.$i > /dev/null
    7. if [ $? -eq 0 ];then
    8. echo "192.168.120.$i is rechable"
    9. else
    10. echo "192.168.120.$i is unrechable"
    11. fi
    12. #let i++
    13. done

    2、批量添加用户

    1. #!/bin/bash
    2. user=$(cat /opt/user.txt)
    3. for i in $user
    4. do
    5. echo "$i"
    6. useradd "$i"
    7. echo $i:$i | chpasswd
    8. #echo "1234" | passwd --stdin $i
    9. done

    注意点:

    • ubuntu 不支持--stdin,要用echo 和 chpasswd结合使用
    • 在ubuntu 上要使用$(cat /opt/user.txt),而不是$`cat /opt/user.txt`, 否则通过for 循环遍历时,第一个数据老是给加上$,比如user.txt第一行的数据是user1,它会变成$user1, 

    有批量添加,就有批量删除

    1. #!/bin/bash
    2. user=$(cat /opt/user.txt)
    3. for i in $user
    4. do
    5. userdel -f $i
    6. done

    3、将1-100中的奇数放入数组

    1. #!/bin/bash
    2. for((i=0;i<=100;i++))
    3. do
    4. if [ $[i%2] -eq 1 ];then
    5. array[$[$[$i-1]/2]]=$i
    6. fi
    7. done
    8. #echo ${array[0]}
    9. echo ${array[*]}

    运行结果

    1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
    

    知识点: 

    • $[] 是用来进行数学运算的,支持+-*%/。效果同$(())
    • $[] 中括号里引用的变量可以不用加$符号,比如上面的 $[i%2]
    • $[i%2]等同于$((i%2))
    • array[*] 表示获取数组中的所有数据

    4、创建任意数字及长度的数组,自定义元素

    1. #!/bin/bash
    2. i=0
    3. while true
    4. do
    5. read -p "input? yes or no:" operate
    6. if [ $operate = no ];then
    7. break
    8. fi
    9. read -p "input the value:" value
    10. array[$i]=$value
    11. let i++
    12. done
    13. echo ${array[*]}

    知识点:

    • [ $doing = no ] 等价于[ $doing = "no" ] , = 是判断字符串的,对于纯字符串所以加不加引号都可

    5、将数组中的数小于60的变成60,高于60的不操作

    1. #!/bin/bash
    2. array=(61 62 63 50 59 64)
    3. count=${#array[*]}
    4. echo before:${array[*]}
    5. for((i=0;i<$count;i++))
    6. do
    7. if [ ${array[$i]} -lt 60 ] ; then
    8. array[$i]=60
    9. fi
    10. done
    11. echo after:${array[*]}

    知识点:

    • 数组的定义中的元素之间用空格分开,不要用逗号(,)
    • 数组的长度用 ${#array[*]} 或 ${#array[@]} 获取
    • 数组元素的获取用 ${array[0]} , 赋值的时候不用加$ {}

    6、判断数组中最大的数

    1. #!/bin/bash
    2. max=0
    3. array=(1 2 5 3 7 9)
    4. count=${#array[*]}
    5. for((i=0;i<$count;i++))
    6. do
    7. if [ ${array[$i]} -gt $max ];then
    8. max=${array[$i]}
    9. fi
    10. done
    11. echo "the max num of array is ${max}"

    知识点:

    •  在取变量的时候需要加$,比如:$max, ${array[0]},再给变量赋值的时候不需要加$比如:max=1, array[0]=1

    7、猜数字

    1. #!/bin/bash
    2. seed=(0 1 2 3 4 5 6 7 8 9)
    3. len=${#seed[*]}
    4. random=$[RANDOM%$len]
    5. guess=${seed[$random]}
    6. while :
    7. do
    8. read -p "0-9? you guess which one? " doing
    9. if [ $doing -eq $guess ]; then
    10. echo "bingo"
    11. exit 0
    12. elif [ $doing -gt $guess ]; then
    13. echo "oops, too big"
    14. else
    15. echo "oops, too small"
    16. fi
    17. done

    知识点

    • $RANDOM 的范围是 [0, 32767] 
    • :空语句相当于true,即 while : 相当于 while true

    8、删除数组中小于60的元素(unset)

    1. #!/bin/bash
    2. num=(58 59 60 61 62)
    3. i=0
    4. for p in ${num[*]}
    5. do
    6. if [ $p -lt 60 ]; then
    7. unset num[$i]
    8. fi
    9. let i++
    10. done
    11. echo the final result is ${num[*]}
    12. exit 0

    知识点:

    • unset 为 shell 内建指令,用于删除定义的可读可写的shell变量(包括环境变量)和shell函数。不能对只读操作。
    1. tt=1
    2. echo $tt
    3. unset tt
    4. echo $tt

    9、求1...100的和

    1. #!/bin/bash
    2. sum=0
    3. for i in {1..100}
    4. do
    5. sum=$[$sum+$i]
    6. done
    7. echo the result is ${sum}
    8. exit 0

    10、求1...50的和(until)

    1. #!/bin/bash
    2. sum=0
    3. i=0
    4. until [ $i -gt 50 ]
    5. do
    6. #sum=$[$sum+$i]
    7. let sum+=$i
    8. let i++
    9. done
    10. echo the result is ${sum}

    知识点:

    • let 命令是 BASH 中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来。

    11、石头,剪刀,布

    1. #!/bin/bash
    2. game=(rock paper sissor)
    3. random=$[$RANDOM%3]
    4. scriptResult=${game[$random]}
    5. echo $scriptResult
    6. echo "choose your result:"
    7. echo "1.rock"
    8. echo "2.paper"
    9. echo "3.sissor"
    10. read -p "choose 1, 2 or 3: " choice
    11. case $choice in
    12. 1)
    13. if [ $[$random+1] -eq 1 ]; then
    14. echo "equal"
    15. elif [ $[$random+1] -eq 2 ]; then
    16. echo "you lose"
    17. else
    18. echo "you win"
    19. fi
    20. ;;
    21. 2)
    22. if [ $[$random+1] -eq 1 ]; then
    23. echo "you win"
    24. elif [ $[$random+1] -eq 2 ]; then
    25. echo "equal"
    26. else
    27. echo "you lose"
    28. fi
    29. ;;
    30. 3)
    31. if [ $[$random+1] -eq 1 ]; then
    32. echo "you lose"
    33. elif [ $[$random+1] -eq 2 ]; then
    34. echo "you win"
    35. else
    36. echo "equal"
    37. fi
    38. ;;
    39. *)
    40. echo "wrong number"
    41. ;;
    42. esac
    43. exit 0

    12、成绩计算(小于60 不及格 85以上优秀)

    1. #!/bin/bash
    2. while :
    3. do
    4. read -p "input score: " score
    5. if [ $score -le 100 ] && [ $score -gt 85 ]
    6. then
    7. echo "great"
    8. elif [[ $score -lt 85 && $score -ge 60 ]]; then
    9. echo "normal"
    10. else
    11. echo "failed"
    12. fi
    13. done
    14. exit 0

    知识点:

    • [ $score -le 100 ] && [ $score -gt 85 ] 等价于 [[ $score -le 100  &&  $score -gt 85 ]] ,双中括号之间不要有空格,[[ ]] 是shell中的关键字,不是命令,单中括号[],是test命令
    • [[ ]] 不需要注意某些细枝末节,比[]功能强大

    • [[ ]] 支持逻辑运算

    • [[ ]] 支持正则表达式

    • [[]] 关键字

    13、计算当前的内存使用百分比

    1. #!/bin/bash
    2. mem_line=$(free -m | grep "Mem")
    3. memory_total=$(echo $mem_line | awk '{print $2}')
    4. memory_used=$(echo $mem_line | awk '{print $3}')
    5. echo "total memory: $memory_total MiB"
    6. echo "used memory: $memory_used MiB"
    7. #echo "usage rate: $[$memory_used/$memory_total * 100]%"
    8. echo "usage rate:" $(echo $mem_line | awk '{printf("%0.2f%", $3 / $2 * 100)}')
    9. exit 0

     知识点:

    1、free -m 命令以MiB为单位打印

    1 MiB = 1024KiB,   1MB=1000KiB

    1. man free
    2. -m, --mebi Display the amount of memory in mebibytes.
    1. total used free shared buff/cache available
    2. Mem: 3876 1182 1518 3 1175 2428
    3. Swap: 923 0 923

    grep "Mem" 会将第二行(Mem开头的那行)抽取出来

    2、awk 会进行文本处理, 利用printf函数处理小数

    awk '{printf("%0.2f%", $3 / $2 * 100)}'

    14、过滤出本机ether网卡的MAC地址

    1. #!/bin/bash
    2. eth=$(ifconfig | grep "ether" | awk '{print $2}')
    3. echo $eth
    4. exit 0

    思路也简单,通过ifconfig 获取ether所在行,通过awk获取对应行的第二个参数$2

    ens37: flags=4163  mtu 1500
            inet6 fe80::5e0a:f1cf:cbf8:4c2d  prefixlen 64  scopeid 0x20
            ether 00:0c:29:f6:b6:99  txqueuelen 1000  (Ethernet)
            RX packets 87  bytes 10378 (10.3 KB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 3992  bytes 720667 (720.6 KB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    lo: flags=73  mtu 65536
            inet 127.0.0.1  netmask 255.0.0.0
            inet6 ::1  prefixlen 128  scopeid 0x10
            loop  txqueuelen 1000  (Local Loopback)
            RX packets 68614  bytes 4911600 (4.9 MB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 68614  bytes 4911600 (4.9 MB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    15、统计/var/log有多少个文件,并显示这些文件名

    1. #!/bin/bash
    2. count=0
    3. for file in $(ls /var/log)
    4. do
    5. echo $file
    6. if [ -f "/var/log/${file}" ]
    7. then
    8. let count++
    9. echo "file name: $file"
    10. else
    11. echo "no file"
    12. fi
    13. done
    14. echo "the count of files is: ${count}"
    15. echo "the count of files is:" `find /var/log -maxdepth 1 -type f |wc -l`
    16. exit 0

    知识点:

    •  如果上述脚本中写成 if [ -f  $file ],就算是文件也会判断失败, file要写成路径的形式,单纯一个名字都会失败,其它文档中写的没有路径,这个注意下

    16、打印字母数小于8的单词

    1. for e in `cat ./nowcoder.txt`
    2. do
    3. if [ ${#e} -lt 8 ];then
    4. echo ${e}
    5. fi
    6. done
    7. exit 0

    知识点

    • ${#} 用于获取字符串或数组的长度,${#var}:字符串长度, ${#array[*]}:数组长度

    17、统计所有进程占用内存百分比的和

    统计所有进程占用内存百分比的和_牛客题霸_牛客网 (nowcoder.com)

    1. #!/bin/bash
    2. sum=0
    3. i=0
    4. for m in `awk '{print $4}' ./nowcoder.txt`
    5. do
    6. if [ $i -eq 0 ];then
    7. let i++
    8. continue
    9. fi
    10. r=$(echo $m | bc)
    11. sum=$(echo $r + $sum | bc)
    12. done
    13. echo $sum | bc
    14. exit 0

    知识点:

    • 利用bc处理小数,这里是利用的+,,$(echo $r + $sum | bc)

    18、统计每个单词出现的个数

    打印无顺序(利用字典)

    1. #!/bin/bash
    2. declare -A dic
    3. for word in `cat nowcoder.txt`
    4. do
    5. if [ $word = "" ];then
    6. continue
    7. fi
    8. if [ -v dic[$word] ]; then
    9. r=${dic[$word]}
    10. dic[$word]=`expr $r + 1`
    11. else
    12. dic[$word]=1
    13. fi
    14. done
    15. for key in `echo ${!dic[*]}`
    16. do
    17. echo "$key ${dic[$key]}"
    18. done
    19. exit 0

    利用文件处理顺序

    1. #!/bin/bash
    2. declare -A dic
    3. for word in `cat nowcoder.txt`
    4. do
    5. if [ $word = "" ];then
    6. continue
    7. fi
    8. if [ -v dic[$word] ]; then
    9. r=${dic[$word]}
    10. dic[$word]=`expr $r + 1`
    11. else
    12. dic[$word]=1
    13. fi
    14. done
    15. rm tmp.txt
    16. touch tmp.txt
    17. for key in `echo ${!dic[*]}`
    18. do
    19. echo "${dic[$key]} $key" >> tmp.txt
    20. done
    21. cat tmp.txt | sort -n |awk '{print $2,$1}'
    22. exit 0

    知识点:

    1、字典声明用declare -A dic

    2、字典赋值dic[key]=value

    3、获取所有key , ${!dic[*]}

    4、获取所有value, ${dic[*]}

    linux 程序设计 第四版 shell 脚本

    已调试,大致没问题,想学习的复制拿去

    1. #!/bin/sh
    2. menu_choice=""
    3. current_cd=""
    4. title_file="title.cdb"
    5. tracks_file="tracks.cdb"
    6. temp_file=/tmp/cdb.$$
    7. trap 'rm -f $temp_file' EXIT
    8. get_return() {
    9. echo "Please return \c"
    10. read x
    11. return 0
    12. }
    13. get_confirm() {
    14. echo -e "Are you sure? \c"
    15. while true
    16. do
    17. read x
    18. case "$x" in
    19. y | yes|Y|Yes|YES) return 0;;
    20. n | no|N|No|NO)
    21. echo
    22. echo "Cancelled"
    23. return 1;;
    24. *) echo "Please enter yes or no";;
    25. esac
    26. done
    27. }
    28. set_menu_choice() {
    29. clear
    30. echo "Options : -"
    31. echo
    32. echo " a) Add new CD"
    33. echo " f) Find CD"
    34. echo " c) Cont the CDs and tracks in the catalog"
    35. if [ "$cdcatnum" != "" ]; then
    36. echo " l) List track on $cdtitle"
    37. echo " r) Remove $cdtitle"
    38. echo " u) Update track information for $cdtitle"
    39. fi
    40. echo " q) Quit"
    41. echo
    42. echo "Please enter choice then press return \c"
    43. read menu_choice
    44. return
    45. }
    46. insert_title() {
    47. echo $* >> $title_file
    48. return
    49. }
    50. insert_track() {
    51. echo $* >> $tracks_file
    52. return
    53. }
    54. add_record_tracks() {
    55. echo "Enter track information for this CD"
    56. echo "When no more tracks enter q"
    57. cdtrack=1
    58. cdtitle=""
    59. while [ "$cdtitle" != "q" ]
    60. do
    61. echo "Track $cdtrack, track title? \c"
    62. read tmp
    63. cdtitle=${tmp%%, *}
    64. echo ${tmp}======
    65. echo ${cdtitle}-------
    66. if [ "$tmp" != "$cdtitle" ]; then
    67. echo "Sorry, no commas allowed"
    68. continue
    69. fi
    70. if [ -n "$cdtitle" ]; then
    71. echo enter
    72. echo ${cdtitle}-------
    73. if [ "${cdtitle}" != "q" ]; then
    74. echo enter1
    75. insert_track $cdcatnum, $cdtrack, $cdtitle
    76. fi
    77. else
    78. cdtrack=$((cdtrack-1))
    79. fi
    80. cdtrack=$((cdtrack+1))
    81. done
    82. }
    83. add_records() {
    84. echo "Enter catalog name \c"
    85. read tmp;
    86. cdcatnum=${tmp%%, *}
    87. echo "Enter title \c"
    88. read tmp
    89. cdtitle=${tmp%%, *}
    90. echo "Enter type \c"
    91. read tmp
    92. cdtype=${tmp%%, *}
    93. echo "Enter artist/composer \c"
    94. read tmp
    95. cdac=${tmp%%, *}
    96. echo About to add new entry
    97. echo "$cdcatnum $cdtitle $cdtype $cdac"
    98. if get_confirm; then
    99. insert_title $cdcatnum, $cdtitle, $cdtype, $cdac
    100. add_record_tracks
    101. else
    102. remove_records
    103. fi
    104. return
    105. }
    106. find_cd() {
    107. if [ "$1" = "n" ] ; then
    108. asklist=n
    109. else
    110. asklist=y
    111. fi
    112. cdcatnu=""
    113. echo -e "Enter a string to search for in the CD titles \c"
    114. read searchstr
    115. if [ "$searchstr" = "" ] ; then
    116. return 0
    117. fi
    118. grep "$searchstr" $title_file > $temp_file
    119. set $(wc -l $temp_file)
    120. linesfound=$1
    121. case "$linesfound" in
    122. 0) echo "Sorry, nothing found"
    123. get_return
    124. return 0;;
    125. 1) ;;
    126. 2) echo "Sorry, not unique"
    127. echo "Found the following"
    128. cat $temp_file
    129. get_return
    130. return 0
    131. esac
    132. IFS=","
    133. read cdcatnum cdtitle cdtype cdac < $temp_file
    134. IFS=" "
    135. if [ -z "$cdcatnum" ]; then
    136. echo "Sorry, cound not extract catalog field from $temp_file"
    137. get_return
    138. return 0
    139. fi
    140. echo
    141. echo Catalog num: $cdcatnum
    142. echo Title: $cdtitle
    143. echo TYPe: $cdtype
    144. echo Artist: $cdac
    145. echo
    146. get_return
    147. if [ "$asklist" = "y" ]; then
    148. echo -e "View tracks for this CD? \c"
    149. if [ "$x" = "y" ]; then
    150. echo
    151. list_tracks
    152. echo
    153. fi
    154. fi
    155. return 1
    156. }
    157. update_cd() {
    158. if [ -z "$cdcatnum" ]; then
    159. echo "You must select a CD first"
    160. find_cd n
    161. fi
    162. if [ -n "$cdcatnum" ]; then
    163. echo "Current tracks are: -"
    164. list_tracks
    165. echo
    166. echo "This will re_enter the tracks for $cdtitle"
    167. get_confirm && {
    168. grep -v "^${cdcatnum}," $tracks_file > $temp_file
    169. mv $temp_file $tracks_file
    170. echo
    171. add_record_tracks
    172. }
    173. fi
    174. return
    175. }
    176. count_cds() {
    177. set $(wc -l $title_file)
    178. num_titles=$1
    179. set $(wc -l $tracks_file)
    180. num_tracks=$1
    181. echo found $num_title CDs, with a total of $num_tracks tracks
    182. get_return
    183. return
    184. }
    185. remove_records() {
    186. if [ -z "$cdcatnum" ]; then
    187. echo You must select a CD first
    188. find_cd n
    189. fi
    190. if [ -n "$cdcatnum" ]; then
    191. echo "You are about to delete $cdtitle"
    192. get_confirm && {
    193. grep -v "^${cdcatnum}," $title_file > $temp_file
    194. mv $temp_file $title_file
    195. grep -v "^${cdcatnum}," $tracks_file > $temp_file
    196. mv $temp_file $tracks_file
    197. cdcatnum=""
    198. echo Entry removed
    199. }
    200. get_return
    201. fi
    202. return
    203. }
    204. list_tracks() {
    205. if [ "$cdcatnum" = "" ]; then
    206. echo no CD selected yet
    207. return
    208. else
    209. grep "^${cdcatnum}," $tracks_file > $temp_file
    210. num_tracks=$(wc -l $temp_file)
    211. if [ "$num_tracks" = "0" ]; then
    212. echo no tracks found for $cdtitle
    213. else {
    214. echo
    215. echo "$cdtitle :-"
    216. echo
    217. cut -f 2- -d, $temp_file
    218. } | ${PAGER:-more}
    219. fi
    220. fi
    221. get_return
    222. return
    223. }
    224. rm -f $temp_file
    225. if [ ! -f $title_file ];then
    226. touch $title_file
    227. fi
    228. if [ ! -f $title_file ]; then
    229. touch $tracks_file
    230. fi
    231. clear
    232. echo
    233. echo
    234. echo "Mini CD manager"
    235. sleep 1
    236. quit=n
    237. while [ "$quit" != "y" ];
    238. do
    239. set_menu_choice
    240. case "$menu_choice" in
    241. a) add_records;;
    242. r) remove_records;;
    243. f) find_cd y;;
    244. u) update_cd;;
    245. c) count_cds;;
    246. l) list_tracks;;
    247. b)
    248. echo
    249. more $title_file
    250. echo
    251. get_return
    252. ;;
    253. q|Q) quit=y;;
    254. *) echo "Sorry, choice not recognized";;
    255. esac
    256. done
    257. rm -f $temp_file
    258. echo "Finished"
    259. exit 0

  • 相关阅读:
    河南大学大数据平台技术实验报告二
    开通一个幻兽帕鲁专用服务器多少钱?阿里云挺便宜
    如何确定IP地址的具体位置?
    linux安装ES
    软件测试基本流程有哪些?北京专业第三方软件检测机构安利
    python——字符串
    央企招聘:中储粮集团2023公开招聘公告(校招+社招,共700人)
    docker部署prometheus+grafana服务器监控(二) - 安装数据收集器 node-exporter
    在PostGIS中检查孤线(Find isolated lines in PostGIS)
    电脑奔溃的时候,到底发生了什么?
  • 原文地址:https://blog.csdn.net/TSC1235/article/details/133847735