voedger / kb

Knowledge base
0 stars 0 forks source link

bash: declare + readonly #16

Open maxim-ge opened 10 months ago

maxim-ge commented 10 months ago

Script 1

#!/usr/bin/env bash

set -Eeuo  pipefail
declare readonly a=10
a=20

Script 2

#!/usr/bin/env bash

set -Eeuo  pipefail
readonly a=10
a=20

Which script will fail?

maxim-ge commented 10 months ago
Answer

Script 1- `declare readonly a=10` means declaration of two variables: `readonly` and `a`, so `a` is not readonly and Script 1 won't fail. This works: ```bash #!/usr/bin/env bash set -Eeuo pipefail declare readonly a=10 declare -p a # Print variable value and type declare -p readonly a=20 ``` This does not: ```bash #!/usr/bin/env bash set -Eeuo pipefail readonly a=10 declare -p a # Print variable value and type declare -p readonly # Will fail here a=20 ``` Oops: avoid using reserved words as variable names in VQL?