initializing arrays in sh

2019-02-25 14:53发布

问题:

I want to initialize an array in sh.

In bash that would be:

list=(`seq 1 4`)

In sh I try to do it like this:

    for i in `seq 1 4`; do
        list[$((i-1))]="$i"
    done

I get an error though for each iteration saying:

list[0]=1: not found

What am I doing wrong and how to fix that?

回答1:

POSIX sh doesn't support arrays. You need a more advanced shell for that, e.g. bash, zsh, or ksh.



回答2:

If you really want to use arrays, you can fudge them by writing your own array function. I'm not going to encourage this by giving you a full function :-) but here's the gist:

$ f0=yay 
$ t=0
$ eval echo f$t
f0
$ eval echo \$f$t
yay