me gustaría establecer elementos de la matriz con el bucle:Shell matrices de guión
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i] = 'sg'
done
echo $array[0]
echo $array[1]
Por lo tanto, no funciona. ¿Cómo ...?
me gustaría establecer elementos de la matriz con el bucle:Shell matrices de guión
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i] = 'sg'
done
echo $array[0]
echo $array[1]
Por lo tanto, no funciona. ¿Cómo ...?
Quitar los espacios:
array[$i]='sg'
Además, debe tener acceso a los elementos como *:
echo ${array[0]}
Véase, por ejemplo http://tldp.org/LDP/abs/html/arrays.html.
hay un problema con su estado de cuenta de eco: dar ${array[0]}
y ${array[1]}
Se debe trabajar si se hubiera declarado la variable como matriz, e imprimirlo correctamente:
declare -a array
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i]="sg"
done
echo ${array[0]}
echo ${array[1]}
verlo en acción here .
HTH
Mi opinión sobre ese bucle:
array=($(yes sg | head -n10))
O aún más simple:
array=(sg sg sg sg sg sg sg sg sg sg)
Ver http://ideone.com/DsQOZ de alguna prueba. Tenga en cuenta también, bash 4+ readarray:
readarray array -t -n 10 < <(yes "whole lines in array" | head -n 10)
De hecho, readarray es más versátil, p. obtener los mejores 10 PIDs de procesos con golpe en el nombre en matriz (que podría volver un tamaño de la matriz < 10 si no hay 10 tales procesos):
readarray array -t -n 10 < <(pgrep -f bash)
añadido readarray, que tiene su lugar para permitir el espacio en blanco incrustado fácilmente – sehe
# Declare Array
NAMEOFSEARCHENGINE=(Google Yahoo Bing Blekko Rediff)
# get length of an array
arrayLength=${#NAMEOFSEARCHENGINE[@]}
# use for loop read all name of search engine
for ((i=0; i<${arrayLength}; i++));
do
echo ${NAMEOFSEARCHENGINE[$i]}
done
de salida:
Google
Yahoo
Bing
Blekko
Rediff
¿Conoces el comando seq? puedes reemplazar tus números con $ (seq 0 9) – Miquel
@Miquel: o simplemente '{0..9}'. –
Debe tener cuidado, ya que algunos shells no tienen arrays. Si desea escribir sh portátil, no puede utilizar matrices en absoluto. –