richo
richo

Reputation: 8989

Iterate over array

In a shell script I'm looking to iterate over an array like I would in python by doing:

for i, j in (("i value", "j value"), ("Another I value", "another j value")):
    # Do stuff with i and j
    print i, j

But can't work out the best way to do it? I'm tempted to rewrite the shell script in python but that seems awfully heavy for what I'm trying to do.

Upvotes: 1

Views: 939

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360105

There are any number of ways to do this. Here's one using a here doc:

foo () {
    while IFS=$1 read i j
    do
        echo "i is $i"
        echo "j is $j"
    done
}

foo '|' <<EOF
i value|j value
Another I value|another j value
EOF

Upvotes: 1

psmears
psmears

Reputation: 28010

In this instance I would do:

while [ $# -ge 2 ]; do
    PATH="$1"; shift
    REPO="$1"; shift
    # ... Do stuff with $PATH and $REPO here
done

Note that each time you reference variables ($1, $PATH, and especially $@, you want to surround them with "" quotes - that way you avoid issues when there are spaces in the values.

Upvotes: 2

richo
richo

Reputation: 8989

Posting here the current kludge I'm using to do it..

#!/bin/bash

function pull_or_clone {
    PATH=$1
    shift
    REPO=$1
    shift

    echo Path is $PATH
    echo Repo is $REPO

    # Do stuff with $PATH and $REPO here..


    #Nasty bashism right here.. Can't seem to make it work with spaces int he string
    RAWP=$@
    RAWP=${#RAWP}
    if [ $RAWP -gt 0 ]; then
        pull_or_clone $@
    fi
}


pull_or_clone path repo pairs go here

Upvotes: 0

Related Questions