Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

arrays in posix shell is missing #47

Open
matu3ba opened this issue Sep 28, 2022 · 0 comments
Open

arrays in posix shell is missing #47

matu3ba opened this issue Sep 28, 2022 · 0 comments

Comments

@matu3ba
Copy link

matu3ba commented Sep 28, 2022

Sometimes it can be extremely convenient to have them and having a simple example would help. Also it might help to show some broken behavior of IFS=\n, which can be very surprising.

# https://stackoverflow.com/a/53747300
s='A|B|C|D' # specify your "array" as a string with a sigil between elements
IFS='|'     # specify separator between elements
set -f      # disable glob expansion, so a * doesn't get replaced with a list of files

getNth()  { shift "$(( $1 + 1 ))"; printf '%s\n' "$1"; }
getLast() { getNth "$(( $(length "$@") - 1 ))" "$@"; }
length()  { echo "$#"; }

length $s   # emits 4
getNth 0 $s # emits A
getNth 1 $s # emits B
getLast $s  # emits D

s2='t1 t2 t3 t4'
set -f; IFS=' '      # IFS='\n' appears to be broken
for jar in ${s2}; do
  set +f; unset IFS
  echo "$jar"        # restore globbing and field splitting at all whitespace
done
set +f; unset IFS    # do it again in case $INPUT was empty
echo "done"
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant