Is it possible to define an array in multiple lines in a shell script file? I tried something like this:
foo.sh
#!/usr/bin/env bash messages=( "Hello" "World" ) echo $messages
However, the output only has the first line "Hello", but not the second line "Word".
$ sh foo.sh Hello
What is more confusing to me is that if I copy the content of foo.sh and paste it directly into the terminal, things work as I expected:
$ messages=( "Hello" "World" ) echo $messages Hello World
Anybody know why?
Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
If you want to print the whole array, you need:
echo ${messages[@]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With