Why does the bash array ignore newline characters?

Possible duplicate:
Example printing in bash does not create a new line

I have a sample script "array-test.sh" that combines three functions into one array:

[ user@host ~]$ cat array-test.sh #!/usr/bin/env bash function1() { printf '%s\n\n\n' "cat" } function2() { printf '%s\n\n\n' "dog" } function3() { printf '%s\n\n\n' "mouse" } for function in\ function1\ function2\ function3; do array[$((index++))]=$($function) done echo "${array[@]}" [ user@host ~]$ ./array-test.sh cat dog mouse [ user@host ~]$ 

However, newline characters are missing. What causes this behavior?

+4
source share
3 answers

As pointed out by ÁlvaroG.Vicario, backticks (and $() ) remove trailing newlines. There does not slip away, so if you need to, you have to get around this:

 #!/usr/bin/env bash function1() { printf '%s' "cat" } function2() { printf '%s' "dog" } function3() { printf '%s' "mouse" } for function in\ function1\ function2\ function3; do array[$((index++))]=$($function) done # manually add three newlines here array=("${array[@]/%/$'\n'$'\n'$'\n'}") echo "${array[@]}" 
+1
source

Another option: add a character ( @ here) at the end of the line. New lines in the middle of the line will be stored in $( ... ) . Then delete the character by expanding the parameter:

 #!/bin/bash function1() { printf '%s\n\n\ n@ ' "cat" } function2() { printf '%s\n\n\ n@ ' "dog" } function3() { printf '%s\n\n\ n@ ' "mouse" } for function in\ function1\ function2\ function3; do array[index++]=$($function) array[index]=${array[index]%@} done echo "${array[@]}" 
+2
source

It appears that the subshell extension reduces newline characters, but only if they occur at the end. Here kludge:

 function3() { printf '%s\n\n\n-' "mouse" } foo=$(function3) foo=${foo%-} echo "$foo" 
+1
source

Source: https://habr.com/ru/post/1446198/


All Articles