bash 如何在 POSIX sh 中标记数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6499486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:15:38  来源:igfitidea点击:

How to mark an array in POSIX sh?

arraysbashposixsh

提问by Charles

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

在 shell 脚本中替换外部命令时,我使用了一个数组来摆脱 awk 的NF.

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

现在,由于我从 bash 转移到 POSIX sh,我无法正确标记数组:

#!/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:

我正在使用 OpenBSD 的 sh,它的大小与 ksh 完全相同。将上面更改为/bin/sh,以下似乎不起作用:

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

我怎么能在/bin/sh. (请注意,如果您使用 bash 调用它可以正常工作--posix,这不是我要找的。)

回答by Matthew Slattery

Arrays are not part of the POSIX shspecification.

数组不是POSIXsh规范的一部分。

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"

回答by Sammy S.

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

您可以使用 Github 中的以下项目,该项目实现了符合 POSIX 标准的数组,该数组适用于我尝试过的所有 shell:https: //github.com/makefu/array

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

使用起来不是很方便,但我发现它很适合我的目的。

回答by ralph

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

以下代码适用于使用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 IFSis set to a space and there are no double quotes around $RANGE.

请注意,IFS设置为空格并且 周围没有双引号$RANGE