
Estoy intentando utilizar matrices en Bourne Shell ( /bin/sh
). Descubrí que la forma de inicializar elementos de la matriz es:
arr=(1 2 3)
Pero se encuentra con un error:
syntax error at line 8: `arr=' unexpected
Ahora, la publicación donde encontré esta sintaxis dice que es para bash
, pero no pude encontrar ninguna sintaxis separada para Bourne Shell. ¿La sintaxis /bin/sh
también es la misma ?
Respuesta1
/bin/sh
Casi nunca hay un shell Bourne en ningún sistema hoy en día (incluso Solaris, que fue uno de los últimos sistemas importantes en incluirlo, ahora ha cambiado a un POSIX sh para su /bin/sh en Solaris 11). /bin/sh
Era el caparazón de Thompson a principios de los años 70. El shell Bourne lo reemplazó en Unix V7 en 1979.
/bin/sh
ha sido el shell Bourne durante muchos años después (o el shell Almquist, una reimplementación gratuita en BSD).
Hoy en día, /bin/sh
es más común un intérprete u otro para el sh
lenguaje POSIX que a su vez se basa en un subconjunto del lenguaje ksh88 (y un superconjunto del lenguaje shell Bourne con algunas incompatibilidades).
El shell Bourne o la especificación del lenguaje POSIX sh no admiten matrices. O más bien , tienen solo una matriz: los parámetros posicionales ( $1
,,, por lo que también hay una matriz por función).$2
$@
ksh88 tenía matrices con las que configuró set -A
, pero no se especificaron en POSIX sh ya que la sintaxis es incómoda y no muy utilizable.
Otros shells con variables de matriz/lista incluyen: csh
/ tcsh
, rc
, es
, bash
(que principalmente copió la sintaxis ksh a la manera ksh93), yash
, zsh
, fish
cada uno con una sintaxis diferente ( rc
el shell del futuro sucesor de Unix, fish
y zsh
siendo el más consistente unos)...
En estándar sh
(también funciona en versiones modernas del Bourne Shell):
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)
(tenga en cuenta que en el shell Bourne y ksh88, $IFS
debe contener el carácter de espacio para "$@"
que funcione correctamente (un error), y en el shell Bourne, no puede acceder a los elementos anteriores $9
( ${10}
no funcionará, aún puede hacerlo shift 1; echo "$9"
o recorrerlo en bucle). a ellos)).
Respuesta2
Como han dicho los demás, el Bourne Shell no tieneverdaderomatrices.
Sin embargo, dependiendo de lo que necesites hacer, las cadenas delimitadas deberían ser suficientes:
sentence="I don't need arrays because I can use delimited strings"
for word in $sentence
do
printf '%s\n' "$word"
done
Si los delimitadores típicos (espacio, tabulación y nueva línea) no son suficientes, puede configurarIFS
a cualquier delimitador que desee antes del ciclo.
Y si necesita crear la matriz mediante programación, puede simplemente crear una cadena delimitada.
Respuesta3
No hay matrices en el shell Bourne simple. Puede utilizar la siguiente forma para crear una matriz y recorrerla:
#!/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
No importa qué forma de usar las matrices sh
elija, siempre será engorroso. Considere usar un idioma diferente, como Python
o, Perl
si puede, a menos que esté atrapado en una plataforma muy limitada o quiera aprender algo.
Respuesta4
Una forma de simular matrices en guión (se puede adaptar para cualquier número de dimensiones de una matriz): (Tenga en cuenta que el uso del seq
comando requiere que IFS
esté configurado en ' ' (ESPACIO = el valor predeterminado). Puede usar while ... do ...
o do ... while ...
en su lugar, bucles para evitar esto (me mantuve seq
en el alcance de una mejor ilustración de lo que hace el código).)
#!/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 ###
################