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

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[@]

  • 1
    echo "${arr[@]}" – Ipor Sircer Dec 6 '18 at 17:29

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 agree to our terms of service, privacy policy and cookie policy

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