Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

bash - How to mark an array in POSIX sh?

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...