Skip to content

Instantly share code, notes, and snippets.

@samy-mahmoudi
Forked from biiont/iterate_shell_array.sh
Last active June 15, 2020 15:41
Show Gist options
  • Save samy-mahmoudi/7fe55cea3390c1676a9a361bacd303d3 to your computer and use it in GitHub Desktop.
Save samy-mahmoudi/7fe55cea3390c1676a9a361bacd303d3 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 "$CAR"'.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment