程式扎記: [Linux 常見問題] Use bash variables in for loop range of bash

標籤

2015年6月1日 星期一

[Linux 常見問題] Use bash variables in for loop range of bash

Source From Here 
Question 
I want to print list of numbers from 1 to 100 and I use a for loop like the following: 
  1. number=100  
  2. for num in {1..$number}  
  3. do  
  4.   echo $num  
  5. done  
When I execute the command it only prints {1..100} and not the list of number from 1 to 100. 

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 
  1. number=10  
  2. i=1  
  3. while [ "$i" -le "$number" ]; do  
  4.   echo "$i"  
  5.   i=$(($i + 1))  
  6. done  
Ksh-style for ((...)) 
  1. for ((i=1;i<=10;i++)); do  
  2.   echo "$i"  
  3. done  
use eval (not recommended) 
  1. number=10  
  2. eval '  
  3.   for i in {1..'"$number"'}; do  
  4.     echo "$i"  
  5.   done  
  6. '  
Use the GNU seq command on systems where it's available 
  1. number=10  
  2. for i in $(seq "$number"); do  
  3.   echo "$i"  
  4. done  
That one being less efficient as it forks and runs a new command and the shell has to reads its output from a pipe 

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

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!