2

I'm building a bash script that gets information from GeekTool and parses the results. The so far the script looks like this:

1  #!/bin/bash
2  
3  clear
4  
5  geeklets=`osascript <<TEXT
6      Tell Application "GeekTool Helper"
7          geeklets
8      End Tell
9  TEXT`
10 
11 IFS="," read -a geekletArray <<< "$geeklets"
12 
13 echo "First Element in Array:"
14 echo ${geekletArray[0]}
15 
16 echo ""
17 
18 echo "All Array Elements:"
19 for element in ${geekletArray[@]}
20 do
21     echo $element
22 done

At line 14 I echo out the first element of the array which returns:

shell geeklet id 49610161-0A3C-49C6-9626-694370DE3101

but on the first iteration of the loop that steps through the array (line 21), the first element array is returned like this:

shell
geeklet
id
49610161-0A3C-49C6-9626-694370DE3101

In the loop the elements are returned in a newline delimited list.

Why is there a difference? Also, if I wanted to grab just the id value of the array (e.g. 49610161-0A3C-49C6-9626-694370DE3101), how would I go about it?

Thanks!

2
  • 1
    for element in "${array[@]}" -- the double quotes are mandatory. Commented Feb 26, 2014 at 3:39
  • ...see also shellcheck.net Commented Feb 26, 2014 at 3:39

2 Answers 2

3
for element in "${geekletArray[@]}"
do
   echo "$element"
done

Judicious use of quotes will protect you from undesired word splitting.

Sign up to request clarification or add additional context in comments.

Comments

2

Quoting of arrays can be confusing. You can sidestep the issue completely by iterating over the array indices instead.

There are lots of ways to pull out the id value from the resulting string. I am assuming it will always be the last part of a space-delimited string. As such, I am using a bash parameter expansion to effectively remove all occurrences of the pattern *

for index in ${!geekletArray[@]}
do
    echo "${geekletArray[$index]}"       # entire element
    echo "${geekletArray[$index]##* }"   # id value only
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.