Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark an array in POSIX sh?

Tags:

While replacing external commands in a shell script, I used an array to get rid of awk's NF.

Now, since I moved from bash to POSIX sh, I cannot get the array marked right:

#!/bin/bash export RANGE="0 1 4 6 8 16 24 46 53" RANGE=($RANGE) echo arrayelements: $((${#RANGE[@]})) LAST=$((${#RANGE[@]}-1)) echo "Last element(replace NF): ${RANGE[$LAST]}"  # ./foo arrayelements: 9 Last element(replace NF): 53 

I'm using OpenBSD's, sh and it has exactly the same size as the ksh. Changing above to /bin/sh, it seems that the following doesn't work:

set -A "$RANGE" set -- "$RANGE" 

How could I realise the above script in /bin/sh? (Note that it works fine if you invoke bash with --posix, that's not what I look for.)

like image 783
Charles Avatar asked Jun 27 '11 22:06

Charles


People also ask

How do you declare an array in SH?

To initialize an array element in a ksh -like shell, you must use syntax array[index]=value . To get all element in array, use ${array[*]} or ${array[@]} . sh does not support array!

Are bash arrays Posix?

Arrays are not POSIX; except for the arguments array, which is; though getting subset arrays from $@ and $* is not (tip: use set -- to re-purpose the arguments array). Writing for various versions of Bash, though, is pretty do-able.

Are there arrays in shell script?

There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.

Which shells are Posix compliant?

Some popular shell languages are POSIX-compliant (Bash, Korn shell), but even they offer additional non-POSIX features which will not always function on other shells. The commands test expression is identical to the command [expression] . In fact, many sources recommend using the brackets for better readability.


2 Answers

Arrays are not part of the POSIX sh specification.

There are various other ways to find the last item. A couple of possibilities:

#!/bin/sh export RANGE="0 1 4 6 8 16 24 46 53" for LAST_ITEM in $RANGE; do true; done echo "Last element(replace NF): $LAST_ITEM" 

or:

#!/bin/sh export RANGE="0 1 4 6 8 16 24 46 53" LAST_ITEM="${RANGE##* }" echo "Last element(replace NF): $LAST_ITEM" 
like image 53
Matthew Slattery Avatar answered Jan 12 '23 08:01

Matthew Slattery


You can use the following project from Github, which implements a POSIX-compliant array, which works in all shells I tried: https://github.com/makefu/array

It is not very convenient to use, but I found it to work well for my purposes.

like image 33
Sammy S. Avatar answered Jan 12 '23 08:01

Sammy S.