1、多线程执行
while read line
do
echo $user
done < user.txt
2、while循环从文件中读取内容:适合处理文件
while read ip
do
{
ping -c1 -W1 $ip &>/dev/null
}&
done < ip.txt
thread=5 #进程个数
tmp_fifofile=/tmp/$$.fifo #创建管道
mkfifo $tmp_fifofile
exec 8<> $tmp_fifofile #打开文件描述符
rm $tmp_fifofile
for i in `seq $thread`
do
echo >&8 #往管道中加入5个空行,加入其他的内容也可以
done
while read ip
do
read -u 8 #每次读一行
{
ping -c1 -W1 $ip &>/dev/null
echo >&8 #处理完后加入一行,使管道中一直有五行
}&
done < ip.txt
wait
exec 8<&- #关闭文件描述符
3、无限循环,:命令执行永久为true
while :
do
#statements
done
while true
do
#statements
done
4、判断:再次确认(输入y/n)
read -p "Are you sure? [y/n]" action
if [[ "$action" = "y" ]]; then
#statements
fi
read -p "Are you sure? [y/n]" action
case $action in
y|Y|YES|yes )
;;
esac
5、判断参数个数
if [[ $# -eq 0 ]]; then
echo "参数个数为0"
exit 1
fi
默认取所有参数$*
for i
do
#statements
done
6、提示用法
usage(){
echo "Usage: `basename $0` (start|stop|restart|safeStart)"
exit -1
}
7、$? : 判断上一个命令执行是否成功
mkdir /usr/local/redis
if [[ $? -eq 0 ]]; then
echo "ok"
fi
7、关联数组
declare -A hosts
while read line
do
type=`echo $line |awk '{print $2}'`
let hosts[$type]++
done </etc/hosts
for i in ${!hosts[@]} #数组索引
do
echo "$i: ${hosts[$i]}"
done
8、select选项
#!/usr/bin/bash
#$PS3赋值来修改提示符
PS3="command(5 for quit):"
select command in disk_partion fs cpu_load mem_util quit
do
case $command in
disk_partion )
fdisk -l
;;
fs )
df -h
;;
cpu_load )
uptime
;;
mem_util )
free -m
;;
quit)
break
;;
*)
echo "erro"
exit -1
esac
done
可以使用循环自定义:
#!/bin/bash
help(){
echo "Command action"
echo " a toggle a bootable flag"
echo " b edit bsd disklabel"
echo " c toggle the dos compatibility flag"
echo " d delete a partition"
echo " g create a new empty GPT partition table"
echo " G create an IRIX (SGI) partition table"
echo " l list known partition types"
echo " m print this menu"
echo " n add a new partition"
echo " o create a new empty DOS partition table"
echo " p print the partition table"
echo " q quit without saving changes"
echo " s create a new empty Sun disklabel"
echo " t change a partition's system id"
echo " u change display/entry units"
echo " v verify the partition table"
echo " w write table to disk and exit"
echo " x extra functionality (experts only)"
}
while [[ true ]]; do
read -p "command(m for help):" command
case $command in
m )
help
;;
q )
exit
;;
* )
help
;;
esac
done