How to mark an array in POSIX sh?

会有一股神秘感。 提交于 2019-11-28 09:54:47

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.

The following code works for me using the Heirloom Bourne Shell:

#!/usr/local/bin/bournesh
# cf. Heirloom Bourne Shell, 
#     http://freshmeat.net/projects/bournesh/
#     http://www.in-ulm.de/~mascheck/bourne/

# use a caret as a pipe symbol to make sure it's a Bourne shell
# cf. http://mywiki.wooledge.org/BourneShell
ls ^ cat 1>/dev/null 2>&1 || 
   { echo 'No true Bourne shell! ... exiting ...'; exit 1; }

IFS=' '
unset RANGE
RANGE="0 1 4 6 8 16 24 46 53"
export IFS RANGE
set -- $RANGE
echo arrayelements: $#
LAST=$#
eval echo "Last element\(replace NF\): \$$#"

Note that IFS is set to a space and there are no double quotes around $RANGE.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!