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.)
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!
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.
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.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With