1、多线程执行
while read linedoecho $userdone < user.txt
2、while循环从文件中读取内容:适合处理文件
while read ipdo{ping -c1 -W1 $ip &>/dev/null}&done < ip.txtthread=5 #进程个数tmp_fifofile=/tmp/$$.fifo #创建管道mkfifo $tmp_fifofileexec 8<> $tmp_fifofile #打开文件描述符rm $tmp_fifofilefor i in `seq $thread`doecho >&8 #往管道中加入5个空行,加入其他的内容也可以donewhile read ipdoread -u 8 #每次读一行{ping -c1 -W1 $ip &>/dev/nullecho >&8 #处理完后加入一行,使管道中一直有五行}&done < ip.txtwaitexec 8<&- #关闭文件描述符
3、无限循环,:命令执行永久为true
while :do#statementsdonewhile truedo#statementsdone
4、判断:再次确认(输入y/n)
read -p "Are you sure? [y/n]" actionif [[ "$action" = "y" ]]; then#statementsfiread -p "Are you sure? [y/n]" actioncase $action iny|Y|YES|yes );;esac
5、判断参数个数
if [[ $# -eq 0 ]]; thenecho "参数个数为0"exit 1fi
默认取所有参数$*for ido#statementsdone
6、提示用法
usage(){echo "Usage: `basename $0` (start|stop|restart|safeStart)"exit -1}
7、$? : 判断上一个命令执行是否成功
mkdir /usr/local/redisif [[ $? -eq 0 ]]; thenecho "ok"fi
7、关联数组
declare -A hostswhile read linedotype=`echo $line |awk '{print $2}'`let hosts[$type]++done </etc/hostsfor i in ${!hosts[@]} #数组索引doecho "$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 quitdocase $command indisk_partion )fdisk -l;;fs )df -h;;cpu_load )uptime;;mem_util )free -m;;quit)break;;*)echo "erro"exit -1esacdone
可以使用循环自定义:
#!/bin/bashhelp(){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 ]]; doread -p "command(m for help):" commandcase $command inm )help;;q )exit;;* )help;;esacdone
