GNU/Linux >> Tutoriales Linux >  >> Linux

Matrices en Unix Bourne Shell?

Estoy tratando de usar matrices en Bourne Shell (/bin/sh ). Descubrí que la forma de inicializar los elementos de la matriz es:

arr=(1 2 3)

Pero está encontrando 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 es la misma para /bin/sh? también?

Respuesta aceptada:

/bin/sh casi nunca es un shell Bourne en ningún sistema hoy en día (incluso Solaris, que fue uno de los últimos sistemas principales en incluirlo, ahora ha cambiado a un POSIX sh para su /bin/sh en Solaris 11). /bin/sh fue la concha Thompson a principios de los 70. El shell Bourne lo reemplazó en Unix V7 en 1979.

/bin/sh ha sido el shell Bourne durante muchos años a partir de entonces (o el shell Almquist, una reimplementación gratuita en BSD).

Hoy en día, /bin/sh es más comúnmente un intérprete u otro para POSIX sh lenguaje que a su vez se basa en un subconjunto del lenguaje de ksh88 (y un superconjunto del lenguaje de shell Bourne con algunas incompatibilidades).

El shell Bourne o la especificación del lenguaje POSIX sh no admiten matrices. O mejor dicho, solo tienen una matriz:los parámetros posicionales ($1 , $2 , [email protected] , así que una matriz por función también).

ksh88 tenía matrices que configuraste con set -A , pero eso no se especificó en POSIX sh ya que la sintaxis es incómoda y no muy útil.

Otros shells con variables de matriz/lista incluyen:csh /tcsh , rc , es , bash (que en su mayoría copió la sintaxis ksh de la manera ksh93), yash , zsh , fish cada uno con una sintaxis diferente (rc el caparazón del futuro sucesor de Unix, fish y zsh siendo los más consistentes)…

En estándar sh (también funciona en versiones modernas del shell Bourne):

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

set -- "[email protected]" more # adding elements to the end of the array

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

printf '<%s>n' "[email protected]" # passing all the elements of the [email protected] array 
                     # as arguments to a command

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

printf '%sn' "$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 '%sn' "$# elements in the array"

printf '%sn' "$*" # 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 "[email protected]" funcione correctamente (un error), y en el shell de Bourne, no puede acceder a los elementos por encima de $9 (${10} no funcionará, todavía puedes hacer shift 1; echo "$9" o hacer un bucle sobre ellos)).

Relacionado:¿$SHELL almacena la ruta al shell predeterminado en Linux?
Linux
  1. 3 scripts de Unix Shell:actividad del usuario, ver procesos, mostrar memoria

  2. ¿Cómo ftp y descargo archivos desde un UNIX Shell Script?

  3. UNIX/Linux:¿Qué es un shell? ¿Cuáles son las diferentes conchas?

  4. Sume una columna de números en el shell de Unix

  5. ¿Cómo configurar permanentemente $PATH en Linux/Unix?

SDF proporciona una cuenta gratuita de Unix Shell y acceso Shell a todos

¿Extensiones de archivo para secuencias de comandos de Unix Shell?

Linux frente a Unix

Matrices en scripts de Shell

¿Cómo ejecutar un script de shell en una consola Unix o terminal Mac?

Agregar caracteres de nueva línea a las variables de shell de Unix