I am using fold to make an array of characters from a string.

INPUT=$1
arr=($(fold -w1 <<< "$INPUT"))
echo "$arr"
echo "$arr[@]"

I use command ./myProgram 1234 to execute the script.

Expected output: 1 2 3 4

What I get: 1 and 1[@]

up vote 2 down vote accepted

You correctly assigned the output to the array, but your de-referencing needs help:

echo "$arr"

Simply outputs the first element of the array, which is 1.

echo "$arr[@]"

Is missing the curly braces that would tell bash that you want to subscript the array; as-is, it's dereferencing $arr to the first element, as above, and then printing [@].

Instead, use (for example):

printf '%s ' "${arr[@]}"

See the bash manual section on Arrays where it says:

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell’s filename expansion operators.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.