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?
- for i in list:
- do
- print i
- done
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:
- for i in 1 2 3; do
- echo "$i"
- done
- listVar="1 2 3"
- for i in $listVar; do
- echo "$i"
- done
- for i in $(echo 1; echo 2; echo 3); do
- echo "$i"
- done
- #!/bin/sh
- array=("item 1" "item 2" "item 3")
- lp=0
- echo -e "\t[Info] Correct:"
- for i in "${array[@]}"; do # The quotes are necessary here
- lp=$((lp+1))
- echo -e "\t$lp=$i"
- done
- list='"item 1" "item 2" "item 3"'
- lp=0
- echo -e "\t[Info] Test1:"
- for i in $list; do
- lp=$((lp+1))
- echo -e "\t$lp=$i"
- done
- lp=0
- echo -e "\t[Info] Test2:"
- for i in "$list"; do
- lp=$((lp+1))
- echo -e "\t$lp=$i"
- done
- lp=0
- echo -e "\t[Info] Test3:"
- for i in ${array[@]}; do
- lp=$((lp+1))
- echo -e "\t$lp=$i"
- done
Supplement
* nixCraft - Bash For Loop Examples
沒有留言:
張貼留言