Linux中shell脚本案例(二)
下面是案例:
1、ping测试IP地址
代码:
1 2 3 4 5 6 |
#!/bin/bash for i in 1 2 3 4 do echo "the number of $i computer is " ping -c 1 192.168.0.$i done |
结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
the number of 1 computer is PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data. --- 192.168.0.1 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 10000ms the number of 2 computer is PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data. --- 192.168.0.2 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 10000ms the number of 3 computer is PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data. --- 192.168.0.3 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 10000ms the number of 4 computer is PING 192.168.0.4 (192.168.0.4) 56(84) bytes of data. --- 192.168.0.4 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 10000ms |
2、打印读取的内容.
代码:
1 2 3 4 5 |
#!/bin/bash while read name do echo $name done |
结果:
1 2 |
test.txt test.txt |
3、从test.sh中读取内容并打印
代码:
1 2 3 4 5 |
#/bin/bash while read line do echo $line done < test.sh |
test.sh代码:
1 |
echo 'hello world!' |
结果:
1 |
echo 'hello world!' |
4、给函数传递参数
代码:
1 2 3 4 5 6 7 8 9 10 |
#/bin/bash p_num () { num=$1 echo $num } for n in $@ do p_num $n done |
结果:
1 2 3 4 |
[root]# ./1.sh 11 22 33 11 22 33 |
5、创建文件夹
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#/bin/bash while : do echo "please input file's name:" read a if test -e /lzqhuang/$a then echo "the file is existing Please input new file name:" else mkdir $a echo "you aye sussesful!" break fi done |
结果:
1 2 3 |
please input file's name: aaa you aye sussesful! |
6、获取本机IP地址
代码:
1 2 |
#/bin/bash ifconfig | grep "inet addr:" | awk '{ print $2 }'| sed 's/addr://g' |
结果:
1 |
127.0.0.1 |
7、查找最大文件
代码:
1 2 3 4 5 6 7 8 9 10 11 |
#/bin/bash a=0 for name in *.* do b=$(ls -l $name | awk '{print $5}') if test $b -ge $a then a=$b namemax=$name fi done echo "the max file is $namemax" |
结果:
1 |
the max file is test.txt |
- Linux中shell脚本案例(一)
- Linux中shell脚本案例(三)