[code]for 變量 in 列表; do 循環體 done
[code]{1..100}這樣就能生成列表了
===========================================
例:
[code]#!/bin/bash # for I in {1..100};do echo $I done
用法:
[code]seq [起始數 [步進長度]] 結束數例:
[code][root@iZ28g26851kZ ~]# seq 1 10 1 2 3 4 5 6 7 8 9 10 [root@iZ28g26851kZ ~]# seq 1 2 10 1 3 5 7 9 [root@iZ28g26851kZ ~]# seq 10 1 2 3 4 5 6 7 8 9 10 [root@iZ28g26851kZ ~]#
[code]#!/bin/bash # for I in `seq 1 2 10`;do echo $I done
記住要用反單引號引起來喲~
例:求1到100的和
[code]#!/bin/bash # sum=0 for I in `seq 100`;do let sum=$sum+$I done echo "sum=${sum}"
那如何才能將一個變量直接申明成整型?
declare就可以直接將變量申明成整型
[code]#!/bin/bash # declare -i sum=0 for I in `seq 100`;do let sum=$sum+$I done echo "sum=${sum}"例:向系統中每一個用戶問好~
[code]#!/bin/bash # for NAME in `cat /etc/passwd | cut -d: -f1`;do echo "hello ${NAME}~" done例:向系統中每一個用戶問好,並顯示其shell~
[code]#!/bin/bash # for NAME in `cat /etc/passwd | cut -d: -f1`;do echo "hello ${NAME}~...........`cat /etc/passwd | grep ^$NAME | cut -d: -f7`" done例:只對系統中shell是bash的用戶問號,
[code]#!/bin/bash # for NAME in `cat /etc/passwd | cut -d: -f1`;do SHELL_NAME=`cat /etc/passwd | grep ^$NAME | cut -d: -f7 | sed -r 's@^/.*/(.*)@\1@g'` if [ $SHELL_NAME == "bash" ];then echo "hello ${NAME}~...........`cat /etc/passwd | grep ^$NAME | cut -d: -f7`" fi done
[code]case SWITCH in value1) statement ... ;; value2) statement ... ;; *) statement ... ;; esac例:
[code]#!/bin/bash # case $1 in start) echo "output start";; "open") echo "output open" ;; "state") echo "output state" ;; *) echo "Usage:help" ;; esac記住,每一個case都是雙分號結尾哦