Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readarray -t option in bash default behavior?

Tags:

arrays

bash

From man bash on readarray:

-t
Remove any trailing newline from a line read, before it is assigned to an array element.

Is -t default behavior for readarray in bash?

I tested it couple of times with -t and without on a file with newlines no difference noticed.

like image 997
Filip Stefanov Avatar asked Jan 18 '17 14:01

Filip Stefanov


1 Answers

There is indeed a difference:

# Newlines are retained as part each array element
$ readarray foo <<EOF
> foo
> bar
> baz
> EOF
$ printf '%s' "${foo[@]}"
foo
bar
baz

# Newlines are stripped
$ readarray -t foo <<EOF
foo
bar
baz
EOF

$ printf '%s' "${foo[@]}"
foobarbaz

The format to printf does not include a newline, so the first example only prints each element on a separate line because each element itself ends with a newline. In the second example, all three elements are printed on the same line.

like image 59
chepner Avatar answered Nov 08 '22 10:11

chepner