一. 帶列表的for循環(huán)
1. 語法
for var in list
do
command
done
注意:list可以是含有空格或者是換行的字串。
- 換行:則可以讀取遍歷一個文件;或者命令輸出時,帶有換行
- 空格:則可以構成一個數(shù)組,或者就是字串
?
2. 例子
2.1. 循環(huán)字串
# bash for_test.sh
this is apple
this is orange
this is banana
# cat for_test.sh
#!/bin/bash
fruits="apple orange banana"
for fruit in ${fruits}
do
echo "this is ${fruit}"
done
?
2.2. 展開或命令替換:數(shù)字循環(huán)
連續(xù)數(shù)字相加
cat for_test.sh
#!/bin/bash
# 1. 使用展開
#for num in {1..5}
sum=0
# 2. 使用命令替換
for num in $(seq 1 100)
do
let "sum+=num"
done
echo $sum
?
從1開始步長為2計算和,即計算1到100的奇數(shù)和
# cat for_test.sh
#!/bin/bash
sum=0
for num in $(seq 1 2 100)
do
let "sum+=num"
done
echo $sum
?
2.3 命令替換(輸出換行)作為list
[ test ] # cat for_test.sh
#!/bin/bash
for ls_name in $(ls)
do
ls -l ${ls_name}
done
[ test ]# bash for_test.sh
-rw-r--r-- 1 root hadoop 0 Oct 13 12:35 11
-rw-r--r-- 1 root hadoop 60 Oct 13 12:36 for_test.sh
?
二. 其他for循環(huán)
1. 不帶列表的循環(huán)
通過參數(shù)的方式給for傳遞變量值文章來源:http://www.zghlxwxcb.cn/news/detail-401530.html
[root@ test]# bash for_test.sh 1 2 3 4
the var is 1
the var is 2
the var is 3
the var is 4
[root@ test]# cat for_test.sh
#!/bin/bash
for var in $@
do
echo the var is $var
done
?文章來源地址http://www.zghlxwxcb.cn/news/detail-401530.html
2. 類C的for循環(huán)
[root@ test]# bash for_test.sh
5050
[root@ test]# cat for_test.sh
#!/bin/bash
sum=0
for (( i=1; i<=100; i++ ))
do
let "sum+=i"
done
echo $sum
到了這里,關于【shell 基礎(11)循環(huán)之for】帶列表:空格子串、換行子串、展開、命令替換、seq;不帶列表:接受參數(shù)、類C的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!