Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Last active December 10, 2015 07:58
Show Gist options
  • Save thinkerbot/4404582 to your computer and use it in GitHub Desktop.
Save thinkerbot/4404582 to your computer and use it in GitHub Desktop.
Iterate PATH
#!/bin/bash
# Not quite as fast as ifs, but pretty good! BASH specific.
path=":/a b/c:::x/y z:/a:/b:/c:/d:/e:/f:/g:/h:/i:/j"
IFS=: read -a arr <<<"$path"
printf "%s\n" "${arr[@]}"
#!/bin/sh
# Probably as good as it gets. Fast, portable. Still doesn't handle empties.
#
# Extra fields
# path=":a::b"
#
# No extra field
# path="a:b:"
#
path=":/a b/c:::x/y z:/a:/b:/c:/d:/e:/f:/g:/h:/i:/j:"
print_path () { printf "%s\n" $@; }
IFS=: print_path "$path"
# Variation - slower
# (export IFS=:; printf "%s\n" $path)
#
# Variation - weirder
# IFS=: eval printf '%s\\n' \$path
#!/bin/sh
# Pretty fast, works. Needs filter for empty dir.
path=":/a b/c:::x/y z:/a:/b:/c:/d:/e:/f:/g:/h:/i:/j:"
while read -r dir; do echo "$dir"; done <<< "${path//:/$'\n'}"
#!/bin/sh
# Faster, does not work for spaces.
path=":/a b/c:::x/y z:/a:/b:/c:/d:/e:/f:/g:/h:/i:/j:"
for dir in ${path//:/$'\n'} ; do echo "$dir" ; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment