Loop through an array of strings in Bash?

来自: Stack Overflow

You can use it like this:

## declare an array variable
declare -a arr=("element1" "element2" "element3")

## now loop through the above array
for i in "${arr[@]}"
do
   echo "$i"
   # or do whatever with individual element of the array
done

# You can access them using echo "${arr[0]}", "${arr[1]}" also

Also works for multi-line array declaration

declare -a arr=("element1"
                "element2" "element3"
                "element4"
                )

Note

Note that the double quotes around "${arr[@]}" are really important. Without them, the for loop will break up the array by substrings separated by any spaces within the strings instead of by whole string elements within the array. ie: if you had declare -a arr=("element 1" "element 2" "element 3"), then for i in ${arr[@]} would mistakenly iterate 6 times since each string becomes 2 substrings separated by the space in the string, whereas for i in "${arr[@]}" would iterate 3 times, correctly, as desired, maintaining each string as a single unit despite having a space in it.

Parse json with default bash only?

来自: ask ubuntu

A: …an example json:-

{
     "people":[
                 {
                     "id":"4568734",
                     "name":"suneel"
                 },
                 {
                     "id":"3678976",
                     "name":"adi"
                  }
             ]
   }

if say ‘name’ then i want array(“suneel” “adi”)

Note: No use of external tool and with just bash commands.

Q: A bash function like below can be used:

function jsonValue() {
    KEY=$1
    num=$2
    awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$KEY'\042/){print $(i+1)}}}' | tr -d '"' | sed -n ${num}p
}

I’ve saved this function as jsonVal and then sourced this file using source jsonVal. You can very well use it within your script.

It expects two arguments. First argument is the property name. If you need all values, skip second argument. If specific value is needed, you can add the second argument as shown below.

[root@localhost Desktop]# cat data.json | jsonValue id
4568734
3678976
[root@localhost Desktop]# cat data.json | jsonValue id 1
4568734
[root@localhost Desktop]# cat data.json | jsonValue id 2
3678976
[root@localhost Desktop]# cat data.json | jsonValue name
suneel
adi
[root@localhost Desktop]# cat data.json | jsonValue name 1
suneel
[root@localhost Desktop]# cat data.json | jsonValue name 2
adi
[root@localhost Desktop]#

Hope this helps.

Note

If a value contains : , } this seems to break :( — @Phill 有中文似乎也会出问题。

Like this post? Share on:


doobom Avatar doobom is write a bug.
Comments

So what do you think? Did I miss something? Is any part unclear? Leave your comments below.

comments powered by Disqus

Keep Reading


Published

Category

Shell

Tags

Stay in Touch

Get New Release Alert