Skip to content

Instantly share code, notes, and snippets.

@biiont
Forked from anonymous/iterate_shell_array.sh
Last active February 7, 2023 18:00
Show Gist options
  • Save biiont/290341b29657c0bb2df6 to your computer and use it in GitHub Desktop.
Save biiont/290341b29657c0bb2df6 to your computer and use it in GitHub Desktop.
Iterate over an array using POSIX Shell
#!/bin/sh
# Iterate over an array using POSIX Shell
# Initial data
ARR="a:b:c:d"
# Iteration. Do whatever is needed instead of 'echo "$VAL"'.
CDR="${ARR}:"; while [ -n "$CDR" ]; do CAR=${CDR%%:*}; echo "$CAR"; CDR=${CDR#*:}; done; unset CAR CDR
# IMPORTANT!!! Add semicolon to the end of an array (IT="${ARR}:") to make stop condition working.
# Otherwise you will get infinite loop.
@Payne-X6
Copy link

Payne-X6 commented May 5, 2020

Nice work! I always tough that prefix/suffix removing in variables is Bash-ism. I would never think of this solution. Again, nice work..
I have took your code and move it into function, here is preview (It's just an idea, still not finished)...
Usage: for_each $ARR do echo for print every element
Code:

for_each () {
   test "$2" == "do" \
     || return 1
   ARR="$1:"
   while test -n "$ARR" ; do
     CAR=${ARR%%:*}
     eval $3 "$CAR"
     ARR=${ARR#*:}
   done
   unset CAR ARR
}

@samy-mahmoudi
Copy link

Yes, nice work!

Forked and revised: you forgot to change $VAL to $CAR in the comment of line 7, at revision 5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment