Question
I want to print list of numbers from 1 to 100 and I use a for loop like the following:
- number=100
- for num in {1..$number}
- do
- echo $num
- done
How-To
Yes, that's because brace-expansion occurs before parameter expansion. Either use another shell like zsh or ksh93 or use an alternative syntax:
Standard (POSIX) sh syntax
- number=10
- i=1
- while [ "$i" -le "$number" ]; do
- echo "$i"
- i=$(($i + 1))
- done
- for ((i=1;i<=10;i++)); do
- echo "$i"
- done
- number=10
- eval '
- for i in {1..'"$number"'}; do
- echo "$i"
- done
- '
- number=10
- for i in $(seq "$number"); do
- echo "$i"
- done
Avoid loops in shells.
Using loops in a shell script are often an indication that you're not doing it right. Most probably, your code can be written some other way.
Supplement
* 鳥哥私房菜 - 學習 Shell Script - 迴圈 (loop)
* Linux Shell Scripting Tutorial (LSST) v1.05r3 - for Loop
* Tutorialspoint - Unix - Shell Loop Control
沒有留言:
張貼留言