如何在 POSIX sh 中标记数组? [英] How to mark an array in POSIX sh?
问题描述
在替换 shell 脚本中的外部命令时,我使用了一个数组来摆脱 awk 的 NF
.
While replacing external commands in a shell script, I used an array to get rid of awk's NF
.
现在,由于我从 bash 转移到 POSIX sh,我无法正确标记数组:
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
我使用的是 OpenBSD 的 sh,它的大小与 ksh 完全相同.把上面改成/bin/sh
,下面好像不行了:
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"
如何在/bin/sh
中实现上述脚本?(请注意,如果您使用 --posix
调用 bash,它可以正常工作,这不是我要寻找的.)
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.)
推荐答案
数组不是 POSIX 的一部分sh
规范.
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"
或:
#!/bin/sh
export RANGE="0 1 4 6 8 16 24 46 53"
LAST_ITEM="${RANGE##* }"
echo "Last element(replace NF): $LAST_ITEM"
这篇关于如何在 POSIX sh 中标记数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!