简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM