Shell for循環

與其餘編程語言相似,Shell支持for循環。

for循環通常格式爲:編程

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

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

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

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

#!/bin/bash


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

運行結果:編程語言

The value is:1
The value is:2
The value is:3
The value is:4
The value is:5
#!/bin/bash

num=1
for str in 'This is a string' 'test'
do
  echo $num
   num=$[$num+1]
   echo $str
done



num=1
for str in 'This is a string'
do
  echo $num
   num=$[$num+1]
   echo $str
done

 

運行結果:oop

1
This is a string
2
test
1
This is a string

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

#!/bin/bash


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



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

運行結果:命令行

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

普通的for循環code

#!/bin/bash
echo `expr 4 \* 4`

for ((i=1; i <= 10; i++))
do
   echo $(expr $i \* 4)
done
~       

 

 

 

 

方法1:
    for 變量 in 常量列表; do 一些命令; done;blog

 

 

for file in $(ls);do echo $file;done

 

for i in 1 2 3 4 5;do echo $i; done;

方法2:
    for (( 變量初始化; 條件判斷; 變量自變 )); do 一些命令; done;
   字符串

for((i=0; i<10; i++)); do echo $i; done
#!/bin/bash

MAX=10

for ((i=0; i < MAX; i++))
do
    echo $i
done




for ((i=0; i < $MAX; i++))
do
    echo $i
done
#/bin/bash


MAX=10

for ((i=0; i < MAX; i++))
do
   echo $(expr $i \* $i)
   echo $[$i * $i]
done
相關文章
相關標籤/搜索