Linux之部分shell脚本练习(二)
while CONDITION;do
statement
done
进入循环:条件满足
退出循环:条件不满足
until CONDITION;do
statment
...
done
#!/bin/bash
#
read -p "Input something:" STRING
while[ $STRING != ‘quit‘];do
echo $STRING | tr ‘a-z‘ ‘A-Z‘
read -p "Input something:" STRING
done
#!/bin/bash
#
read -p "Input something:" STRING
until [$STRING == ‘quit‘];do
echo $STRING | tr ‘a-z‘ ‘A-Z‘
read -p "Input something:" STRING
done
#!/bin/bash
所以使用的while的时候都可以使用until。
#!/bin/bash
#
who | grep "hadoop" &>/dev/null
RETVAL=$?
until [$RETVAL -eq 0];do
echo "hadoop has not come"
sleep 5
who | grep "hadoop" &>/dev/null
RETVAL=$?
done
echo "hadoop is loggd in"
执行命令状态返回值可以直接引用,并且可以不用加引号。
如果条件部分是执行命令的话,就需要引号。
for循环
for 变量 in 列表;do
循环体
done
近C语言的写法
for((expr1;expr2;expr3)); do
循环体
done
#!/bin/bash
#
declare -i SUM=0
for I in {1..100};do
let SUM+=$I
done
echo $SUM
#!/bin/bash
#
declare -i SUM2=0
for((J=1; J<=100; J++));do
let SUM2+=$J
done
echo $SUM
硬盘,假设它为/dev/sdb),为指定的硬盘创建分区。
1.列出当前系统上所有的硬盘,让用户选择,如果选择quit则退出脚本;如果用户选择错误,就让用户重新选择。
2.当用户选择后,提醒用户确认接下来的操作可能会损坏数据,并请用户确认;如果用户选择y就继续;否则,就让用户重新选择。
3.抹除那块硬盘的所有分区(提示:抹除所有分区执行sync命令,并让脚本睡眠3秒钟后再分区),并为其创建三个主分区,第一个为20M。第二个为512M,第三个为128M,且第三为swap分区类型(提示:将分区模块通过echo传送fdisk即可实现)
#!/bin/bash
#
echo "Initial a disk..."
echo -e "033[31mWarning:\033[0m"
fdisk -l 2> /dv/null | grep -o "^Disk /dev/[sb][a-z]"
read -p "Your choice:" PARTDISK
if [ $PARTDISK == ‘quit‘ ];then
echo "quit"
exit 7
fi
until fdisk -l 2> /dev/null | grep -o "^Disk /dev/[sb][a-z]" | grep "Disk $PARTDISK" &>/dv/null;do
read -p "Wrong option.your choice aging:" PARTDISK
done
read -p "Will destroy all data,continue:" CHOICE
until [ $CHOICE == ‘y‘ -o $CHOICE == ‘n‘ ];do
read -p "Will destroy all data,continue:" CHOICE
done
if [ $CHOICE == ‘n‘ ];then
echo "Quit"
exit 9
else
dd if=/dev/zero of=$PARTDISK 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 $PARTDISK &>/dev/null
sync
sleep 2
partprobe $PARTDISK &>/dev/null
mke2fs -j ${PARTDISK} &>/dev/null
mke2fs -j ${PARTDISK}1 &>/dev/null
mke2fs -j ${PARTDISK}2 &>/dev/null
fi