linux之shell脚本练习
以下脚本已经是在ubuntu下测试的
demo持续更新中。。。
1、for 循环测试,,,Ping 局域网
#!/bin/bashi=1
for i in {1..254}
do# 每隔0.3s Ping 一次,每次超时时间3s,Ping的结果直接废弃ping-w 3 -i 0.3 192.168.110.$i > /dev/nullif [ $? -eq 0 ];thenecho "192.168.120.$i is rechable"elseecho "192.168.120.$i is unrechable"fi#let i++
done
2、批量添加用户
#!/bin/bashuser=$(cat /opt/user.txt)for i in $user
doecho "$i"useradd "$i"echo $i:$i | chpasswd#echo "1234" | passwd --stdin $i
done
注意点:
- ubuntu 不支持--stdin,要用echo 和 chpasswd结合使用
- 在ubuntu 上要使用$(cat /opt/user.txt),而不是$`cat /opt/user.txt`, 否则通过for 循环遍历时,第一个数据老是给加上$,比如user.txt第一行的数据是user1,它会变成$user1,
有批量添加,就有批量删除
#!/bin/bashuser=$(cat /opt/user.txt)for i in $user
douserdel -f $i
done
3、将1-100中的奇数放入数组
#!/bin/bashfor((i=0;i<=100;i++))
doif [ $[i%2] -eq 1 ];thenarray[$[$[$i-1]/2]]=$ifi
done
#echo ${array[0]}
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、创建任意数字及长度的数组,自定义元素
#!/bin/bashi=0while true
doread -p "input? yes or no:" operateif [ $operate = no ];thenbreakfiread -p "input the value:" valuearray[$i]=$valuelet i++
doneecho ${array[*]}
知识点:
- [ $doing = no ] 等价于[ $doing = "no" ] , = 是判断字符串的,对于纯字符串所以加不加引号都可
5、将数组中的数小于60的变成60,高于60的不操作
#!/bin/basharray=(61 62 63 50 59 64)
count=${#array[*]}echo before:${array[*]}
for((i=0;i<$count;i++))
do
if [ ${array[$i]} -lt 60 ] ; thenarray[$i]=60
fi
doneecho after:${array[*]}
知识点:
- 数组的定义中的元素之间用空格分开,不要用逗号(,)
- 数组的长度用 ${#array[*]} 或 ${#array[@]} 获取
- 数组元素的获取用 ${array[0]} , 赋值的时候不用加$ {}
6、判断数组中最大的数
#!/bin/bashmax=0
array=(1 2 5 3 7 9)
count=${#array[*]}for((i=0;i<$count;i++))
doif [ ${array[$i]} -gt $max ];thenmax=${array[$i]}fi
doneecho "the max num of array is ${max}"
知识点:
- 在取变量的时候需要加$,比如:$max, ${array[0]},再给变量赋值的时候不需要加$比如:max=1, array[0]=1
7、猜数字
#!/bin/bashseed=(0 1 2 3 4 5 6 7 8 9)
len=${#seed[*]}
random=$[RANDOM%$len]
guess=${seed[$random]}while :
doread -p "0-9? you guess which one? " doingif [ $doing -eq $guess ]; thenecho "bingo"exit 0elif [ $doing -gt $guess ]; thenecho "oops, too big"else echo "oops, too small"fidone
知识点
- $RANDOM 的范围是 [0, 32767]
- :空语句相当于true,即 while : 相当于 while true
8、删除数组中小于60的元素(unset)
#!/bin/bashnum=(58 59 60 61 62)i=0
for p in ${num[*]}
doif [ $p -lt 60 ]; thenunset num[$i]filet i++
doneecho the final result is ${num[*]}
exit 0
知识点:
- unset 为 shell 内建指令,用于删除定义的可读可写的shell变量(包括环境变量)和shell函数。不能对只读操作。
tt=1
echo $tt
unset tt
echo $tt
9、求1...100的和
#!/bin/bashsum=0
for i in {1..100}
dosum=$[$sum+$i]
doneecho the result is ${sum}
exit 0
10、求1...50的和(until)
#!/bin/bashsum=0
i=0until [ $i -gt 50 ]
do#sum=$[$sum+$i]let sum+=$ilet i++
doneecho the result is ${sum}
知识点:
- let 命令是 BASH 中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来。
11、石头,剪刀,布
#!/bin/bashgame=(rock paper sissor)
random=$[$RANDOM%3]
scriptResult=${game[$random]}echo $scriptResultecho "choose your result:"
echo "1.rock"
echo "2.paper"
echo "3.sissor"read -p "choose 1, 2 or 3: " choicecase $choice in1)if [ $[$random+1] -eq 1 ]; thenecho "equal"elif [ $[$random+1] -eq 2 ]; thenecho "you lose"elseecho "you win"fi;;2)if [ $[$random+1] -eq 1 ]; thenecho "you win"elif [ $[$random+1] -eq 2 ]; thenecho "equal"elseecho "you lose"fi;;3)if [ $[$random+1] -eq 1 ]; thenecho "you lose"elif [ $[$random+1] -eq 2 ]; thenecho "you win"elseecho "equal"fi;;*)echo "wrong number";;esacexit 0
12、成绩计算(小于60 不及格 85以上优秀)
#!/bin/bashwhile :
doread -p "input score: " scoreif [ $score -le 100 ] && [ $score -gt 85 ]thenecho "great"elif [[ $score -lt 85 && $score -ge 60 ]]; thenecho "normal"elseecho "failed"fi
doneexit 0
知识点:
- [ $score -le 100 ] && [ $score -gt 85 ] 等价于 [[ $score -le 100 && $score -gt 85 ]] ,双中括号之间不要有空格,[[ ]] 是shell中的关键字,不是命令,单中括号[],是test命令
-
[[ ]] 不需要注意某些细枝末节,比[]功能强大
-
[[ ]] 支持逻辑运算
-
[[ ]] 支持正则表达式
-
[[]] 关键字
13、计算当前的内存使用百分比
#!/bin/bashmem_line=$(free -m | grep "Mem")
memory_total=$(echo $mem_line | awk '{print $2}')
memory_used=$(echo $mem_line | awk '{print $3}')echo "total memory: $memory_total MiB"
echo "used memory: $memory_used MiB"
#echo "usage rate: $[$memory_used/$memory_total * 100]%"
echo "usage rate:" $(echo $mem_line | awk '{printf("%0.2f%", $3 / $2 * 100)}')exit 0
知识点:
1、free -m 命令以MiB为单位打印
1 MiB = 1024KiB, 1MB=1000KiB
man free-m, --mebi Display the amount of memory in mebibytes.
total used free shared buff/cache available
Mem: 3876 1182 1518 3 1175 2428
Swap: 923 0 923
grep "Mem" 会将第二行(Mem开头的那行)抽取出来
2、awk 会进行文本处理, 利用printf函数处理小数
awk '{printf("%0.2f%", $3 / $2 * 100)}'
14、过滤出本机ether网卡的MAC地址
#!/bin/basheth=$(ifconfig | grep "ether" | awk '{print $2}')echo $ethexit 0
思路也简单,通过ifconfig 获取ether所在行,通过awk获取对应行的第二个参数$2
ens37: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::5e0a:f1cf:cbf8:4c2d prefixlen 64 scopeid 0x20<link>
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 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
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、
linux 程序设计 第四版 shell 脚本
已调试,大致没问题,想学习的复制拿去
#!/bin/shmenu_choice=""
current_cd=""
title_file="title.cdb"
tracks_file="tracks.cdb"
temp_file=/tmp/cdb.$$
trap 'rm -f $temp_file' EXITget_return() {echo "Please return \c"read xreturn 0
}get_confirm() {echo -e "Are you sure? \c"while truedoread xcase "$x" iny | yes|Y|Yes|YES) return 0;;n | no|N|No|NO) echoecho "Cancelled"return 1;;*) echo "Please enter yes or no";;esacdone}set_menu_choice() {clearecho "Options : -"echoecho " a) Add new CD"echo " f) Find CD"echo " c) Cont the CDs and tracks in the catalog"if [ "$cdcatnum" != "" ]; thenecho " l) List track on $cdtitle"echo " r) Remove $cdtitle"echo " u) Update track information for $cdtitle"fiecho " q) Quit"echo echo "Please enter choice then press return \c"read menu_choicereturn
}insert_title() {echo $* >> $title_filereturn
}insert_track() {echo $* >> $tracks_filereturn
}add_record_tracks() {echo "Enter track information for this CD"echo "When no more tracks enter q"cdtrack=1cdtitle=""while [ "$cdtitle" != "q" ] doecho "Track $cdtrack, track title? \c"read tmpcdtitle=${tmp%%, *}echo ${tmp}======echo ${cdtitle}-------if [ "$tmp" != "$cdtitle" ]; thenecho "Sorry, no commas allowed"continuefiif [ -n "$cdtitle" ]; thenecho enterecho ${cdtitle}-------if [ "${cdtitle}" != "q" ]; thenecho enter1insert_track $cdcatnum, $cdtrack, $cdtitlefielsecdtrack=$((cdtrack-1))ficdtrack=$((cdtrack+1))done
}add_records() {echo "Enter catalog name \c"read tmp;cdcatnum=${tmp%%, *}echo "Enter title \c"read tmpcdtitle=${tmp%%, *}echo "Enter type \c"read tmpcdtype=${tmp%%, *}echo "Enter artist/composer \c"read tmpcdac=${tmp%%, *}echo About to add new entryecho "$cdcatnum $cdtitle $cdtype $cdac"if get_confirm; theninsert_title $cdcatnum, $cdtitle, $cdtype, $cdacadd_record_trackselseremove_recordsfireturn
}find_cd() {if [ "$1" = "n" ] ; then asklist=nelseasklist=yficdcatnu=""echo -e "Enter a string to search for in the CD titles \c"read searchstrif [ "$searchstr" = "" ] ; thenreturn 0figrep "$searchstr" $title_file > $temp_fileset $(wc -l $temp_file)linesfound=$1case "$linesfound" in0) echo "Sorry, nothing found"get_returnreturn 0;;1) ;;2) echo "Sorry, not unique"echo "Found the following"cat $temp_fileget_returnreturn 0esacIFS=","read cdcatnum cdtitle cdtype cdac < $temp_fileIFS=" "if [ -z "$cdcatnum" ]; thenecho "Sorry, cound not extract catalog field from $temp_file"get_returnreturn 0fiechoecho Catalog num: $cdcatnumecho Title: $cdtitleecho TYPe: $cdtypeecho Artist: $cdacechoget_returnif [ "$asklist" = "y" ]; thenecho -e "View tracks for this CD? \c"if [ "$x" = "y" ]; thenecholist_tracksechofi fireturn 1
}update_cd() {if [ -z "$cdcatnum" ]; thenecho "You must select a CD first"find_cd nfiif [ -n "$cdcatnum" ]; then echo "Current tracks are: -"list_tracksechoecho "This will re_enter the tracks for $cdtitle"get_confirm && {grep -v "^${cdcatnum}," $tracks_file > $temp_filemv $temp_file $tracks_fileechoadd_record_tracks}fireturn
}count_cds() {set $(wc -l $title_file)num_titles=$1set $(wc -l $tracks_file)num_tracks=$1echo found $num_title CDs, with a total of $num_tracks tracksget_returnreturn
}remove_records() {if [ -z "$cdcatnum" ]; thenecho You must select a CD firstfind_cd nfiif [ -n "$cdcatnum" ]; thenecho "You are about to delete $cdtitle"get_confirm && {grep -v "^${cdcatnum}," $title_file > $temp_filemv $temp_file $title_filegrep -v "^${cdcatnum}," $tracks_file > $temp_filemv $temp_file $tracks_filecdcatnum=""echo Entry removed}get_returnfireturn
}list_tracks() {if [ "$cdcatnum" = "" ]; thenecho no CD selected yetreturnelsegrep "^${cdcatnum}," $tracks_file > $temp_filenum_tracks=$(wc -l $temp_file)if [ "$num_tracks" = "0" ]; thenecho no tracks found for $cdtitleelse {echoecho "$cdtitle :-"echo cut -f 2- -d, $temp_file} | ${PAGER:-more}fifiget_returnreturn
}rm -f $temp_fileif [ ! -f $title_file ];thentouch $title_file
fiif [ ! -f $title_file ]; thentouch $tracks_file
ficlear
echo
echo
echo "Mini CD manager"
sleep 1quit=n
while [ "$quit" != "y" ];
doset_menu_choicecase "$menu_choice" ina) add_records;;r) remove_records;;f) find_cd y;;u) update_cd;;c) count_cds;;l) list_tracks;;b) echomore $title_fileechoget_return;; q|Q) quit=y;;*) echo "Sorry, choice not recognized";;esac
donerm -f $temp_file
echo "Finished"
exit 0