Массивы в Unix Bourne Shell

Массивы в Unix Bourne Shell

Я пытаюсь использовать массивы в оболочке Bourne ( /bin/sh). Я обнаружил, что способ инициализации элементов массива такой:

arr=(1 2 3)

Но возникает ошибка:

syntax error at line 8: `arr=' unexpected

Теперь пост, где я нашел этот синтаксис, говорит, что это для bash, но я не смог найти никакого отдельного синтаксиса для оболочки Bourne. Синтаксис стоит так же для /bin/shтакже?

решение1

/bin/shв настоящее время вряд ли когда-либо есть оболочка Bourne на каких-либо системах (даже Solaris, которая была одной из последних крупных систем, включавших ее, теперь перешла на POSIX sh для своего /bin/sh в Solaris 11). /bin/shбыла оболочкой Thompson в начале 70-х. Оболочка Bourne заменила ее в Unix V7 в 1979 году.

/bin/shна протяжении многих лет после этого использовалась оболочка Bourne (или оболочка Almquist, бесплатная повторная реализация на BSD).

В настоящее время /bin/shчаще всего используется интерпретатор или другой интерпретатор shязыка POSIX, который сам по себе основан на подмножестве языка ksh88 (и надмножестве языка оболочки Bourne с некоторыми несовместимостями).

Оболочка Bourne или спецификация языка POSIX sh не поддерживают массивы. Или, скорее, у них есть только один массив: позиционные параметры ( $1, $2, $@, так что по одному массиву на функцию).

В ksh88 были массивы, которые можно было задать с помощью set -A, но это не было указано в POSIX sh, поскольку синтаксис неудобен и не очень удобен.

Другие оболочки с переменными массивов/списков включают: csh/ tcsh, rc, es, bash(которые в основном скопировали синтаксис ksh в стиле ksh93), yash, zsh, fishкаждая из которых имеет свой синтаксис ( rcоболочка некогда будущего преемника Unix, fishи zshявляющаяся наиболее последовательной)...

В стандартной комплектации sh(также работает в современных версиях оболочки Bourne):

set '1st element' 2 3 # setting the array

set -- "$@" more # adding elements to the end of the array

shift 2 # removing elements (here 2) from the beginning of the array

printf '<%s>\n' "$@" # passing all the elements of the $@ array 
                     # as arguments to a command

for i do # looping over the  elements of the $@ array ($1, $2...)
  printf 'Looping over "%s"\n' "$i"
done

printf '%s\n' "$1" # accessing individual element of the array.
                   # up to the 9th only with the Bourne shell though
                   # (only the Bourne shell), and note that you need
                   # the braces (as in "${10}") past the 9th in other
                   # shells (except zsh, when not in sh emulation and
                   # most ash-based shells).

printf '%s\n' "$# elements in the array"

printf '%s\n' "$*" # join the elements of the array with the 
                   # first character (byte in some implementations)
                   # of $IFS (not in the Bourne shell where it's on
                   # space instead regardless of the value of $IFS)

(обратите внимание, что в оболочке Bourne и ksh88 $IFSдля правильной работы необходимо наличие символа пробела "$@"(ошибка), а в оболочке Bourne вы не сможете получить доступ к элементам выше $9( ${10}не будет работать, вы все равно можете выполнить shift 1; echo "$9"или выполнить цикл по ним)).

решение2

Как уже сказали другие, у Bourne Shell нетистинныймассивы.

Однако, в зависимости от того, что вам нужно сделать, может быть достаточно и строк с разделителями:

sentence="I don't need arrays because I can use delimited strings"
for word in $sentence
do
  printf '%s\n' "$word"
done

Если типичных разделителей (пробел, табуляция и новая строка) недостаточно, вы можете задатьIFSна любой разделитель, который вы хотите перед циклом.

А если вам нужно построить массив программно, вы можете просто создать строку с разделителями.

решение3

В простой оболочке Bourne нет массивов. Вы можете использовать следующий способ для создания массива и его обхода:

#!/bin/sh
# ARRAY.sh: example usage of arrays in Bourne Shell

array_traverse()
{
    for i in $(seq 1 $2)
    do
    current_value=$1$i
    echo $(eval echo \$$current_value)
    done
    return 1
}

ARRAY_1=one
ARRAY_2=two
ARRAY_3=333
array_traverse ARRAY_ 3

Какой бы способ использования массивов shвы ни выбрали, он всегда будет громоздким. Рассмотрите возможность использования другого языка, например Pythonили , Perlесли можете, если только вы не застряли на очень ограниченной платформе или не хотите чему-то научиться.

решение4

Способ имитации массивов в Dash (его можно адаптировать для любого количества измерений массива): (Обратите внимание, что для использования команды seqтребуется, чтобы IFSбыло установлено значение ' ' (SPACE = значение по умолчанию). Вместо этого вы можете использовать циклы while ... do ...или do ... while ..., чтобы избежать этого (я оставил это seqв рамках лучшей иллюстрации того, что делает код).)

#!/bin/sh

## The following functions implement vectors (arrays) operations in dash:
## Definition of a vector <v>:
##      v_0 - variable that stores the number of elements of the vector
##      v_1..v_n, where n=v_0 - variables that store the values of the vector elements

VectorAddElementNext () {
# Vector Add Element Next
# Adds the string contained in variable $2 in the next element position (vector length + 1) in vector $1

    local elem_value
    local vector_length
    local elem_name

    eval elem_value=\"\$$2\"
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    vector_length=$(( vector_length + 1 ))
    elem_name=$1_$vector_length

    eval $elem_name=\"\$elem_value\"
    eval $1_0=$vector_length
}

VectorAddElementDVNext () {
# Vector Add Element Direct Value Next
# Adds the string $2 in the next element position (vector length + 1) in vector $1

    local elem_value
    local vector_length
    local elem_name

    eval elem_value="$2"
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    vector_length=$(( vector_length + 1 ))
    elem_name=$1_$vector_length

    eval $elem_name=\"\$elem_value\"
    eval $1_0=$vector_length
}

VectorAddElement () {
# Vector Add Element
# Adds the string contained in the variable $3 in the position contained in $2 (variable or direct value) in the vector $1

    local elem_value
    local elem_position
    local vector_length
    local elem_name

    eval elem_value=\"\$$3\"
    elem_position=$(($2))
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    if [ $elem_position -ge $vector_length ]; then
        vector_length=$elem_position
    fi

    elem_name=$1_$elem_position

    eval $elem_name=\"\$elem_value\"
    if [ ! $elem_position -eq 0 ]; then
        eval $1_0=$vector_length
    fi
}

VectorAddElementDV () {
# Vector Add Element
# Adds the string $3 in the position $2 (variable or direct value) in the vector $1

    local elem_value
    local elem_position
    local vector_length
    local elem_name

    eval elem_value="$3"
    elem_position=$(($2))
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    if [ $elem_position -ge $vector_length ]; then
        vector_length=$elem_position
    fi

    elem_name=$1_$elem_position

    eval $elem_name=\"\$elem_value\"
    if [ ! $elem_position -eq 0 ]; then
        eval $1_0=$vector_length
    fi
}

VectorPrint () {
# Vector Print
# Prints all the elements names and values of the vector $1 on sepparate lines

    local vector_length

    vector_length=$(($1_0))
    if [ "$vector_length" = "0" ]; then
        echo "Vector \"$1\" is empty!"
    else
        echo "Vector \"$1\":"
        for i in $(seq 1 $vector_length); do
            eval echo \"[$i]: \\\"\$$1\_$i\\\"\"
            ###OR: eval printf \'\%s\\\n\' \"[\$i]: \\\"\$$1\_$i\\\"\"
        done
    fi
}

VectorDestroy () {
# Vector Destroy
# Empties all the elements values of the vector $1

    local vector_length

    vector_length=$(($1_0))
    if [ ! "$vector_length" = "0" ]; then
        for i in $(seq 1 $vector_length); do
            unset $1_$i
        done
        unset $1_0
    fi
}

##################
### MAIN START ###
##################

## Setting vector 'params' with all the parameters received by the script:
for i in $(seq 1 $#); do
    eval param="\${$i}"
    VectorAddElementNext params param
done

# Printing the vector 'params':
VectorPrint params

read temp

## Setting vector 'params2' with the elements of the vector 'params' in reversed order:
if [ -n "$params_0" ]; then
    for i in $(seq 1 $params_0); do
        count=$((params_0-i+1))
        VectorAddElement params2 count params_$i
    done
fi

# Printing the vector 'params2':
VectorPrint params2

read temp

## Getting the values of 'params2'`s elements and printing them:
if [ -n "$params2_0" ]; then
    echo "Printing the elements of the vector 'params2':"
    for i in $(seq 1 $params2_0); do
        eval current_elem_value=\"\$params2\_$i\"
        echo "params2_$i=\"$current_elem_value\""
    done
else
    echo "Vector 'params2' is empty!"
fi

read temp

## Creating a two dimensional array ('a'):
for i in $(seq 1 10); do
    VectorAddElement a 0 i
    for j in $(seq 1 8); do
        value=$(( 8 * ( i - 1 ) + j ))
        VectorAddElementDV a_$i $j $value
    done
done

## Manually printing the two dimensional array ('a'):
echo "Printing the two-dimensional array 'a':"
if [ -n "$a_0" ]; then
    for i in $(seq 1 $a_0); do
        eval current_vector_lenght=\$a\_$i\_0
        if [ -n "$current_vector_lenght" ]; then
            for j in $(seq 1 $current_vector_lenght); do
                eval value=\"\$a\_$i\_$j\"
                printf "$value "
            done
        fi
        printf "\n"
    done
fi

################
### MAIN END ###
################

Связанный контент