Bash: "invalid number" error when passing array elements value to variable

1.9k Views Asked by At

I run GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu). A very simple script called from cmd line with at least 3 arbitrary arguments:

#!/bin/bash

n_arg=$#
arr=("$@") 
AA=${arr[0]}   # CHANGED FROM AA=S{arr[0]}
BB=${arr[1]}   # CHANGED FROM BB=S{arr[1]}

for (( i = 2; i < "$n_arg"; i++ )); do
    printf "%d   %s   %s   %s\n" $i $AA $BB  ${arr[i]}  # <- line 9
    # printf "%d   %s   %s   %s\n" $i "$AA" "$BB"  ${arr[i]}  # ALSO TRIED
done
exit 0

yields an error as shown below:

$ script.sh 10 2 13 443
./script.sh: line 9: printf: S{arr[0]}: invalid number
./script.sh: line 9: printf: S{arr[1]}: invalid number
2    0   0   13
./script.sh: line 9: printf: S{arr[0]}: invalid number
./script.sh: line 9: printf: S{arr[1]}: invalid number
3    0   0   443

I can see that the value of the first and second array elements passed to AA and BB respectively seems to pose a prbm I don't quite scope. I did try: AA="S{arr[0]}" When I type in the code in interactive mode, everything goes smoothly.

1

There are 1 best solutions below

2
On BEST ANSWER

S looks like $, especially when you're tired. I use a font designed to clearly distinguish homoglyphs like that -- highly recommended.

Arrays are not part of the POSIX shell standard. You can roll your own polyfill, or use a pre-fab one.