象while, until, 和for循環代碼塊, 甚至if/then測試結構的代碼塊, 均可以對stdin進行重定向. 即便函數也能夠使用這種重定向方式(請參考例子 23-11). 要想作到這些, 都要依靠代碼塊結尾的<操做符.函數
while循環的重定向 while [ "$name" != Smith ] # 爲何變量$name要用引號? do read name # 從$Filename文件中讀取輸入, 而不是在stdin中讀取輸入. echo $name let "count += 1" done <"$Filename" # 重定向stdin到文件$Filename. 重定向while循環的另外一種形式 exec 3<&0 # 將stdin保存到文件描述符3. exec 0<"$Filename" # 重定向標準輸入. count=0 while [ "$name" != Smith ] do read name # 從stdin(如今已是$Filename了)中讀取. echo $name let "count += 1" done # 從文件$Filename中循環讀取 重定向for循環 for name in `seq $line_count` # "seq"打印出數字序列. # while [ "$name" != Smith ] -- 比"while"循環更復雜-- do read name # 從$Filename中, 而非從stdin中讀取. echo $name if [ "$name" = Smith ] # 由於用for循環, 因此須要這個多餘測試. then break fi done <"$Filename" 重定向for循環(stdin和stdout都進行重定向) for name in `seq $line_count` do read name echo "$name" if [ "$name" = "$FinalName" ] then break fi done < "$Filename" > "$Savefile" # 重定向stdin到文件$Filename, # 而且將它保存到備份文件中.