Pseudo-arrays for POSIX shell
Par Julien Fontanet le vendredi 24 septembre 2010, 17h46 :: Lien permanent
Hi everyone,
I recently wrote a script and I needed to use arrays.
Unfortunately, there are no arrays in the POSIX shell specification. But, after some research I found a way to use pseudo-arrays.
The first trick is to use the set command which permits to modify the values of the positional parameters. You will therefor be able to get the number of elements ($#), access any items (for the n-th item: $n) or iterate through them. The only thing I don't know is how to change the value of one of them.
The second trick is to properly quote the various elements you want to put in it. To do that I wrote a small function (which I won't describe here) which is able substitute a substring by another one in a string. I used this function to replace each occurrence of a single quote by “a single quote + an escaped single quote + a single quote” in my items and I enclosed them between two single quotes.
Here is an example of how using it.
#!/bin/sh . jfsh.sh # Contains the quote function (and subst which is used by it) print_arrays() { local array entry for array do eval "set -- $array" # Loads the array contained in $1 printf '%d elements\n' $# for entry do printf ' “%s”\n' "$entry" done done } reverse_array() { local entry result eval "set -- $1" for entry do result="$(quote "$entry") $result" done printf '%s\n' "$result" } array1="$(quote 1 "second element" "third one")" # This array will contains the filenames of every files in this directory. array2="$(quote *)" # We can apply a function on array1. array3="$(reverse_array "$array1")" # Let's print the various arrays. print_arrays "$array1" "$array2" "$array3"
The file “jfsh.sh” is available on github.