程式扎記: [Linux 常見問題] Shell - Does linux shell support list data structure?

標籤

2016年3月3日 星期四

[Linux 常見問題] Shell - Does linux shell support list data structure?

Source From Here 
Question 
I know lots of script language support list structure, such as python, python, ruby, and javascript, so what about linux shell? does shell support such syntax? 
  1. for i in list:  
  2. do  
  3.      print i  
  4. done  
How-To 
It supports lists, but not as a separate data structure (ignoring arrays for the moment). The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally: 
  1. for i in 1 2 3do  
  2.     echo "$i"  
  3. done  
or via parameter expansion: 
  1. listVar="1 2 3"  
  2. for i in $listVar; do  
  3.     echo "$i"  
  4. done  
or command substitution: 
  1. for i in $(echo 1; echo 2; echo 3); do  
  2.     echo "$i"  
  3. done  
An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference: 
  1. #!/bin/sh  
  2. array=("item 1" "item 2" "item 3")  
  3. lp=0  
  4. echo -e "\t[Info] Correct:"  
  5. for i in "${array[@]}"do   # The quotes are necessary here  
  6.     lp=$((lp+1))  
  7.     echo -e "\t$lp=$i"  
  8. done  
  9.   
  10. list='"item 1" "item 2" "item 3"'  
  11. lp=0  
  12. echo -e "\t[Info] Test1:"  
  13. for i in $list; do  
  14.     lp=$((lp+1))  
  15.     echo -e "\t$lp=$i"  
  16. done  
  17.   
  18. lp=0  
  19. echo -e "\t[Info] Test2:"  
  20. for i in "$list"do  
  21.     lp=$((lp+1))  
  22.     echo -e "\t$lp=$i"  
  23. done  
  24.   
  25. lp=0  
  26. echo -e "\t[Info] Test3:"  
  27. for i in ${array[@]}; do  
  28.     lp=$((lp+1))  
  29.     echo -e "\t$lp=$i"  
  30. done  
Execution result: 
# ./test.sh
[Info] Correct:
1=item 1
2=item 2
3=item 3
[Info] Test1:
1="item
2=1"
3="item
4=2"
5="item
6=3"
[Info] Test2:
1="item 1" "item 2" "item 3"
[Info] Test3:
1=item
2=1
3=item
4=2
5=item
6=3


Supplement 
nixCraft - Bash For Loop Examples

沒有留言:

張貼留言

網誌存檔

關於我自己

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