鍍金池/ 教程/ Linux/ Shell for 循環(huán)
Shell 特殊變量:Shell $0, $#, $*, $@, $?, $$和命令行參數(shù)
Shell 文件包含
Shell 輸入輸出重定向:Shell Here Document,/dev/null
Shell 函數(shù)參數(shù)
Shell 簡(jiǎn)介
Shell printf命令:格式化輸出語(yǔ)句
第一個(gè) Shell 腳本
Shell echo 命令
Shell 運(yùn)算符:Shell 算數(shù)運(yùn)算符、關(guān)系運(yùn)算符、布爾運(yùn)算符、字符串運(yùn)算符等
Shell 數(shù)組:shell 數(shù)組的定義、數(shù)組長(zhǎng)度
Shell until 循環(huán)
Shell if else 語(yǔ)句
Shell 變量:Shell 變量的定義、刪除變量、只讀變量、變量類型
Shell 字符串
Shell 與編譯型語(yǔ)言的差異
Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)
Shell 替換
Shell case esac 語(yǔ)句
Shell for 循環(huán)
什么時(shí)候使用 Shell
Shell 注釋
幾種常見的 Shell
Shell while 循環(huán)
Shell break 和 continue 命令

Shell for 循環(huán)

與其他編程語(yǔ)言類似,Shell 支持 for 循環(huán)。

for 循環(huán)一般格式為:

for 變量 in 列表
do
    command1
    command2
    ...
    commandN
done

列表是一組值(數(shù)字、字符串等)組成的序列,每個(gè)值通過(guò)空格分隔。每循環(huán)一次,就將列表中的下一個(gè)值賦給變量。

in 列表是可選的,如果不用它,for 循環(huán)使用命令行的位置參數(shù)。

例如,順序輸出當(dāng)前列表中的數(shù)字:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

運(yùn)行結(jié)果:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

順序輸出字符串中的字符:

for str in 'This is a string'
do
    echo $str
done

運(yùn)行結(jié)果:

This is a string

顯示主目錄下以 .bash 開頭的文件:

#!/bin/bash

for FILE in $HOME/.bash*
do
   echo $FILE
done

運(yùn)行結(jié)果:

/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc