for循环内使用迭代变量

#!/bin/bash
for i in {1..5}
do
   echo "$i"
done

1.1 错误写法

引入变量的错误写法1):

#!/bin/bash
START=1
END=5
for i in {$START..$END}
do
   echo "$i"
done

1.2 修正

for循环中使用eval

for循环内使用eval:

#!/bin/bash
START=1
END=5
for i in $(eval echo "{$START..$END}")
do
	echo "$i"
done

2.1 方式一:c++

#!/bin/bash
START=1
END=5
echo "Countdown"
 
for (( c=$START; c<=$END; c++ ))
do
	echo -n "$c "
	sleep 1
done
 
echo
echo "Boom!"

2.2 方式二:while-do-done

#!/bin/bash
START=1
END=5
## save $START, just in case if we need it later ##
i=$START
while [[ $i -le $END ]]
do
    echo "$i"
    ((i = i + 1))
done

#!/bin/bash
 
## define an array ##
arrayname=( Dell HP Oracle )
 
## get item count using ${arrayname[@]} ##
for m in "${arrayname[@]}"
do
  echo "${m}"
  # do something on $m #
done

输出:

Dell
HP
Oracle


1)
$START和$END会赋值,但for不会产生循环区间了.
  • linux/shell/for.txt
  • 最后更改: 2019/04/16 18:31
  • (外部编辑)