Bash arrays and pathname expansion: Weird output

303 views Asked by At

I have two files in my home directory .phpsh and .php_history and using their names I wanted to test the expansion of pathnames and how it affects associative arrays in bash. The results I came across seemed weird and I couldn't quite explain them. I've tried a whole bunch of variations here.

 >my_array_filename_var=(".phpsh"=10 ".php_history" =20)
 >echo ${my_array_filename_var[.phpsh]}
 ERROR
 >echo "${my_array_filename_var[.phpsh]}"
 ERROR
 # This one below understandably doesn't work. But I was pulling my hair out.
 >echo "${my_array_filename_var[".phpsh"]}"
 ERROR
 echo "${my_array_filename_var[\".phpsh\"]}"
 ERROR
 >echo "${my_array_filename_var[.phpsh]}"
 ERROR
 >echo "${my_array_filename_var[phpsh]}"
 .phpsh=10
 >echo "${my_array_filename_var[php_history]}"
 .phpsh=10
 >echo "${my_array_filename_var[\.php_history]}"
 ERROR

where the ERROR token stands for

bash: .phpsh: syntax error: operand expected (error token is ".phpsh")

Is there some rule that says I can't have the dot character in my key for an associative array? How does pathname expansion in the bash play with this?

1

There are 1 answers

0
user000001 On BEST ANSWER

You should declare -A (capital A) an associative array in bash. This is the correct syntax:

$ declare -A my_array_filename_var=([.phpsh]=10 [.php_history]=20)
$ echo "${my_array_filename_var[.phpsh]}"
10

Or

$ declare -A my_array_filename_var
$ my_array_filename_var=([.phpsh]=10 [.php_history]=20)
$ echo "${my_array_filename_var[.phpsh]}"
10