Shell for循環


與其他編程語言類似,Shell支持for循環。

for循環一般格式為:

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

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

in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。

例如,順序輸出當前列表中的數字:

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

運行結果:

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


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

  1. for str in 'This is a string'
  2. do
  3. echo $str
  4. done

運行結果:

This is a string


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

  1. #!/bin/bash
  2. for FILE in $HOME/.bash*
  3. do
  4. echo $FILE
  5. done

運行結果:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM