writing a bash array (of strings and special chars) to a file

arrays, bash

Solution

`bash` does not interpret C-style backslash escapes (`\n`) in quoted strings.

Instead, use the `bash` syntax `$'\n'`:

OUTARRAY[j]=$'\n'
OUTARRAY[j]="${INARRAY[i]}"$'\t'

You might find it more readable if you start by defining:

NL=$'\n'
TAB=$'\t'

and then you can insert `${NL}` and `${TAB}` freely inside your double-quoted strings.

Alternatively, you can use a bash extension:

`printf` normally expands C-style backslash escapes in formats, but not in arguments. However, if you are using bash, then you can use the bash-specific `%b` `printf` format which expands backslash escapes in the corresponding argument. I don't really endorse this solution, but it should work without other modifications:

printf "%b" "${OUTARRAY[@]}" > ${OUTFILE}

By the way, it is not really good style to use ALL CAPS for bash variable names, because it increases the probability that they will clash with bash/system-specific environment variables.

Problem

I have a bash array `OUTARRAY` that I fill will values from processing an `INARRAY`. I frequently append to `OUTARRAY` special chars, namely `\t` and `\n` so it may look like: ``` OUTARRAY[j]="\n" ``` or ``` OUTARRAY[j]="${INARRAY[i]}\t" ``` in the end I dump the `OUTARRAY` in a file using ``` printf "%s" "${OUTARRAY[@]}" > ${OUTFILE} ``` the result I get however is, a single line file with all the special chars printed within: ``` \n2771\t2899\t7624\t2911\t\n2772\t2904\t7706\t2911\t\n2771\t2909 ``` Instead, I want columned output. Something like ``` 2771 2899 7624 2911 2772 2904 7706 2911 ``` and so on. what do I do wrong? thank you

Original source