Snažím se používat pole v Bourne shellu (/bin/sh ). Zjistil jsem, že způsob inicializace prvků pole je:
arr=(1 2 3)
Ale dochází k chybě:
syntax error at line 8: `arr=' unexpected
Nyní příspěvek, kde jsem našel tuto syntaxi, říká, že je pro bash , ale nemohl jsem najít žádnou samostatnou syntaxi pro Bourne shell. Je syntaxe stejná pro /bin/sh také?
Přijatá odpověď:
/bin/sh je v dnešní době stěží Bourne shell na jakémkoli systému (dokonce i Solaris, který byl jedním z posledních velkých systémů, který jej obsahoval, nyní přešel na POSIX sh pro svůj /bin/sh v Solaris 11). /bin/sh byl Thompsonův granát na počátku 70. let. Bourne shell jej nahradil v Unixu V7 v roce 1979.
/bin/sh byl Bourne shell po mnoho let poté (nebo Almquist shell, bezplatná reimplementace na BSD).
V současné době /bin/sh je více obyčejně interpret nebo jiný pro POSIX sh jazyk, který je sám o sobě založen na podmnožině jazyka ksh88 (a nadmnožině jazyka Bourne shell s některými nekompatibilitami).
Bourne shell nebo specifikace jazyka POSIX sh nepodporují pole. Nebo spíše mají pouze jedno pole:poziční parametry ($1 , $2 , [email protected] , takže také jedno pole na funkci).
ksh88 měl pole, která jste nastavili pomocí set -A , ale to nebylo specifikováno v POSIX sh, protože syntaxe je nešikovná a málo použitelná.
Mezi další shelly s proměnnými pole/seznamy patří:csh /tcsh , rc , es , bash (který většinou kopíroval syntaxi ksh způsobem ksh93), yash , zsh , fish každý s jinou syntaxí (rc shell kdysi budoucího nástupce Unixu, fish a zsh jsou nejdůslednější)…
Ve standardním sh (funguje také v moderních verzích Bourne shellu):
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)
(všimněte si, že v Bourne shell a ksh88, $IFS musí obsahovat znak mezery pro "[email protected]" správně fungovat (chyba) a v Bourne shellu nemáte přístup k prvkům nad $9 (${10} nebude fungovat, stále můžete provést shift 1; echo "$9" nebo přes ně smyčka)).