Found this strange behavior difference in Bash, between explicit and implicit declarations of variables.

An implicit variables declaration statement resolve back-references to variables from the same statement.

Whereas:

An explicit variables declaration statement does not resolve back-reference variables from the same statement.

Illustration code:

==== knip code start
#!/usr/bin/env bash

unset a b c
printf $'\nExplicit declarations statements:\n'
printf $'\ntypeset -i a=2 b=$a c="$((a - 1))":\n=> '
typeset -i a=2 b=$a c="$((a - 1))"
printf 'a=%d b=%d c=%d\n' "${a}" "${b}" "${c}"
unset a b c
printf $'\ndeclare a=hello b=world c="$a $b":\n=> '
declare a='hello' b='world' c="${a} ${b}"
printf $"a='%s' b='%s' c='%s'\\n" "${a}" "${b}" "${c}"

unset a b c
printf $'\nImplicit declarations statements:\n'
a=2 b=$a c="$((a - 1))"
printf $'\na=2 b=$a c="$((a - 1))":\n=> '
printf 'a=%d b=%d c=%d\n' "${a}" "${b}" "${c}"
unset a b c
a='hello' b='world' c="${a} ${b}"
printf $'\na=hello b=world c="$a $b":\n=> '
printf $"a='%s' b='%s' c='%s'\\n" "$a" "$b" "$c"
==== knip code end

Output:
bash ./test_declare.sh
Explicit declarations statements:

typeset -i a=2 b=$a c="$((a - 1))":
=> a=2 b=0 c=-1

declare a=hello b=world c="$a $b":
=> a='hello' b='world' c=' '

Implicit declarations statements:

a=2 b=$a c="$((a - 1))":
=> a=2 b=2 c=1

a=hello b=world c="$a $b":
=> a='hello' b='world' c='hello world'


ksh93 resolves explicit back-references with typeset.

--
Léa Gris



Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to