首页 > 代码库 > linux命令练习:脚本实现硬盘分区功能
linux命令练习:脚本实现硬盘分区功能
练习一
1、通过ping命令测试10.109.134.233到10.109.134.249之间的所有主机是否在线;
如果在线,就显示“ip is up ” 其中的IP要换成真正的IP地址,且以绿色显示;
如果不在线,就显示“ip is down”其中的IP要换成真正的IP地址,且以红色显示;
要求:分别使用whil,until和for(两种形式)循环实现。
for第一种形式
#!/bin/bash
# program:
# 测试ip地址是否在线
# history donggen 2016-11-08-15:55
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
for ((i=233;i<249;i++));do
ping -c 1 -W 1 10.109.134.$i
P=$?
[ $P -eq 0 ] && echo "\033[32m10.109.134.$i\033[0m is up" || echo -e "\033[31m 10.109.134.$i \033[0m is down"
done
for第二种形式
#!/bin/bash
# program:
# 测试ip地址是否在线
# history donggen 2016-11-08-15:55
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
for I in {233..249}; do
ping -c 1 -W 1 10.109.134.$I &> /dev/null
RESULT=$?
[ $RESULT -eq 0 ] && echo -e"\033[32m 10.109.134.$I is up\033[0m" || echo -e"\033[31m 10.109.134.$I is down\033[0m"
done
until循环
#!/bin/bash
# program:
# 练习使用until循环进行ping命令
#history donggen 2016-11-08-17:30
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
declare -i i=232
until [ $i -ge 249 ] ; do
let i+=1
ping -c 1 -W 1 10.109.134.$i &> /dev/null
RESULT=$?
[ $RESULT -eq 0 ] && echo -e "\033[32m10.109.134.$i is up.\033[0m" || echo -e "\033[31m10.109.134.$i is down.\033[0m"
done
while循环
#!/bin/bash
#program:
#练习使用while循环
#history donggen 2016-11-09-08:45
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
declare -i i=232
while [ $i -ge 232 -a $i -le 249 ]; do
let i++
ping -c 1 -W 1 10.109.134.$i &> /dev/null
RESULT=$?
[ $RESULT -eq 0 ] && echo -e "\033[32m10.109.134.$i is up.\033[0m" || echo -e "\033[31m10.109.134.$i is down.\033[0m"
done
练习二
2、写一个脚本(前提:请为虚拟机新增一块硬盘,假设它为/dv/sdb),为指定的硬盘创建分区;
1、列出当前系统上所有的磁盘,让用户选择,如果选择quit则退出脚本;如果用户选择错误,就让用户重新选择;
2、当用户选择后,提醒用户确认接下来的操作可能会损坏数据,并请用户确认;如果用户选择y就继续,否则让用户重新选择;
3、抹除那块硬盘上的所有分区(提示,抹除所有分区后执行sync命令,并让脚本睡眠3秒
钟后再分区);并为其创建三个主分区,第一个为20M,第二个为512M,第三个未128M,且第三个为swap分区类型;(提示:将分区命令通过echo传送给fdisk即可实现)
#!/bin/bash
# program:
# 练习脚本分区
# history donggen 2016-11-09-9:10
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
fdisk -l 2> /dev/null | grep "^Disk /dev/[sh]d[a-z]" | awk -F: ‘{print $1}‘
read -p "Input your choice: " CHOICE
if [ $CHOICE = ‘quit‘ ]; then
echo "choice is quiting.."
exit 6
fi
until fdisk -l 2> /dev/null | grep -o "Disk /dev/[sh]d[a-z]" | grep "^Disk $CHOICE" &> /dev/null; do
read -p "Input your choice again: " CHOICE
done
read -p "Please Continue y|n:" RESULT
until [ $RESULT == "y" -o $RESULT == "n" ]; do
read -p "Please Continue again y|n:" RESULT
done
if [ $RESULT == "n" ]; then
echo "Quiting..."
exit 7
elif [ $RESULT == "y" ]; then
dd if=/dev/zero of=$CHOICE bs=512 count=1
sync
sleep 3
echo ‘n
p
1
+20M
n
p
2
+512M
n
p
3
+128M
t
3
82
w‘| fdisk $CHOICE
echo "$CHOICE is fdisk ok"
fi
本文出自 “学linux历程” 博客,请务必保留此出处http://woyaoxuelinux.blog.51cto.com/5663865/1871115
linux命令练习:脚本实现硬盘分区功能