Alex_DeLarge
Alex_DeLarge

Reputation: 345

How to put * and whitespace in a Bash array?

I'm trying to build an ASCII array, for a brute-force script, and i need to put * and a whitespace in the array, but nothing seems to works.

I've tried this:

array[5]=*
array[5]="*"
array[5]='*'
array[5]=\*
array[5]="\*"
array[5]='\*'

but all of this commands expands * to all files in current working directory, or at least put a "*" in the array.

Same story for whitespace. How can I solve this?

Upvotes: 1

Views: 52

Answers (1)

chepner
chepner

Reputation: 531718

The following assignments behave identically:

array[5]=*
array[5]="*"
array[5]='*'

because pathname expansion is not performed on the RHS of an assignment. However, pathname expansion is performed on the unquoted expansion of a parameter:

$ echo "${array[5]}"
*
$ echo ${array[5]}
[every file in the current directory]

The RHS of an assignment also does not undergo word-splitting, but you still need to quote literal whitespace.

$ foo="a b"
$ bar=$foo
$ printf '%s\n' "$bar"
a b
$ printf '%s\n' $bar
a
b

Upvotes: 3

Related Questions