for循环有2种常用语法格式
for i in `ls /`;do echo $i; done
for((i=1;i<10;i++));do echo $i; done
while循环有一种常用语法
while read line;do echo $line done < /etc/passwd
case 语句有一种常见用法
echo -n "type your machine:" read i case $i in unix) echo "your machine is unix"; ;; linux) echo "echo your machine is linux"; ;; *) echo "your machine is other"; esac
Bash shell的各种循环
首先确定该shell为Bash:
# echo $SHELL
- C语法格式的for循环
for((i=0; i<10; i++));do echo $i done
- 使用seq命令
for i in $(seq 10);do echo $i done
- while-do格式的循环
i=1 while(($i<10));do echo $i i=`expr $i + 1` done
- for…i…in格式的循环
for i in {1..10};do echo $i done
for i in {01..10};do echo $i done
for i in {a..z};do echo $i done
- for格式的另一种循环(命令执行结果/手动指定)
for i in $(ls);do echo $i done
for i in `ls`;do echo $i done
for i in f1 f2 f3;do echo $i done
- cat和while...read格式的循环
cat /tmp/drops.txt | while read url title do title=$(echo $title | tr ' </' '_') curl -s $url | sed -n '/<div id="content">/,/entry-tags/p' >/tmp/tmp.html cat /tmp/top.html /tmp/tmp.html /tmp/bottom.html >/tmp/$title.html done
while read url title do title=$(echo $title | tr ' </' '_') curl -s $url | sed -n '/<div id="content">/,/entry-tags/p' >/tmp/tmp.html cat /tmp/top.html /tmp/tmp.html /tmp/bottom.html >/tmp/$title.html done < /tmp/drops.txt
- 嵌套循环
dir=(papers tips tools news web pentesting database binary) dir_num=${#dir[@]} for((i=0;i<$dir_num;i++)) do for j in $(seq 1 15) do if [ "$j" == 1 ] then echo http://drops.wooyun.org/category/${dir[i]} else echo http://drops.wooyun.org/category/${dir[i]}/page/$j fi done done
arr=("a" "b" "c") echo "arr is (${arr[@]})"
arr=(a b c) for i in ${arr[@]} do echo $i done
echo "参数 $* 表示脚本输入的所有参数:"$* for i in $* ; do echo $i done
Bash在循环读取文件内容时跳过空行/注释行
搜索关键字:linux bash skip blank comment line
参考解答:
- http://www.linuxquestions.org/questions/linux-newbie-8/how-can-i-cat-or-grep-a-file-to-ignore-lines-starting-with-654683/
- http://stackoverflow.com/questions/11267015/how-to-ignore-blank-lines-and-comment-lines-using-awk
- http://stackoverflow.com/questions/17392869/how-to-print-a-file-excluding-comments-and-blank-lines-using-grep-sed
- http://stackoverflow.com/questions/114814/count-non-blank-lines-of-code-in-bash
cat filename | grep -v '^#' | grep -v '^$' cat filename | grep -Ev '^(#|$)' cat filename | grep -Ev '(^#|^\s*$)' cat filename | grep -v '^$\|^\s*\#' awk '!/^ *#/ && NF' filename cat filename | sed '/^\s*#/d;/^\s*$/d'
=EOF=