2

I have a array like this "Apple Banana Clementine Date"

I have to print like this:

1. Apple
2. Banana
3. Clementine
4. Date

Script file:

for i in "${fruits[@]}"; do
    echo "$lineno. $i "
    lineno+=1
done

output of myscript:

1.             Apple
               Banana
               Clem....

I don't understand why it is not printing lineno and also why it is printing long gap b/w 1. and Apple. Thanks.

3
  • How did you create your array?
    – cuonglm
    Nov 28, 2014 at 9:59
  • it's out of some commands @cuonglm
    – gangadhars
    Nov 28, 2014 at 10:00
  • Please show us how did you create your array, I think that's your problem, not quotes.
    – cuonglm
    Nov 28, 2014 at 10:02

2 Answers 2

2

The problem is your array. It seems that you have created an array with only one element. Try this example:

array=("$(printf 'Apple\nBanana\nClementine\nDate')")

for ((i = 0; i < ${#array[@]}; i++)); do
  printf '%d. %s\n' $((i+1)) "${array[$i]}"
done

j=0
for e in "${array[@]}"; do
  j=$((j+1))
  printf '%d. %s\n' "$j" "$e"
done

k=0
for e in ${array[@]}; do
  k=$((k+1))
  printf '%d. %s\n' "$k" "$e"
done

Then run:

$ ./test.sh 
1. Apple
Banana
Clementine
Date
1. Apple
Banana
Clementine
Date
1. Apple
2. Banana
3. Clementine
4. Date

You can see, you actually create an array contains one element. The 3rd loop print four elements because the shell had performed field splitting on string Apple\nBanana\nClementine\nDate, which gave you four separated words back.

If you change the array to:

set -f
array=( $(printf 'Apple\nBanana\nClementine\nDate') )
set +f

(set -f disables wildcard expansion, in case the characters *?\[ appear in the output of the command) you will get the desired result, which is that the output of the command is split at whitespace:

$ ./test.sh 
1. Apple
2. Banana
3. Clementine
4. Date
1. Apple
2. Banana
3. Clementine
4. Date
1. Apple
2. Banana
3. Clementine
4. Date

A note that you must use double quotes "${array[@]}" when you want to iterate through all array elements, or use the c-style for loop like my first example.

4
  • networks=$(iwlist wlan0 scan | grep ESSID | sed -r 's/(ESSID:|")//g'). networks is my array
    – gangadhars
    Nov 28, 2014 at 10:24
  • What shell do you use?
    – cuonglm
    Nov 28, 2014 at 10:26
  • I'm using bash. y?
    – gangadhars
    Nov 28, 2014 at 10:27
  • @linux_inside networks=$(iwlist …) sets networks to a scalar value, which is the output of the command. If you want the output to be split, you need to make the variable an array: networks=($(iwlist …)). Nov 29, 2014 at 20:48
0

This is what you need:

[sreeraj@server ~]$ fruits=(Apple Banana Clementine Date)
[sreeraj@server ~]$ (IFS=$'\n'; echo "${fruits[*]}") | nl
     1  Apple
     2  Banana
     3  Clementine
     4  Date
[sreeraj@server ~]$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .