Reputation: 497
I'm trying to print out some data from my code as a debug tool in bash. So I want to store all data in an array were I later on print it out.
So far I have setup printf with some arguments:
DATA_ARRAY+=("\n%-5s %-10s %-15s %-10s %-5s %-5s %-5s %-120s" "data1" "data2" "data3" "data4" "data5" "data6" "data7" "data8")
were data is a random text in this case. This will give me a nice column based text in the terminal.
However the other data may look somewhat simpler:
DATA_ARRAY+=("\n%-s" "[Remove] \ID: $dataID Data missing -> Removing $dataID")
My final line is to print all with printf
printf "${REMOVE_DATA_ARRAY[*]}"
.
So my problem now is that all the data will not keep the structure when I print it and it react to characters such as "s" and "i".
So my question is, is it possible to do this without escaping each character (s,i) and print the hole array with the given structure above.
I do not want to print each part at a time.
The program does work if I do
printf ("\n%-5s %-10s %-15s %-10s %-5s %-5s %-5s %-120s" "data1" "data2" "data3" "data4" "data5" "data6" "data7" "data8")
Directly but this is not what I want to do.
Upvotes: 1
Views: 1479
Reputation: 35116
How about splitting the format string and data into 2 separate variables:
MYFMT
: (simple variable) append successive format strings onto the end of this variableDATA_ARRAY
: (array) append successive items to the end of this arrayUsing the samples from the question we get:
$ MYFMT="\n%-5s %-10s %-15s %-10s %-5s %-5s %-5s %-120s"
$ DATA_ARRAY=("data1" "data2" "data3" "data4" "data5" "data6" "data7" "data8")
$ dataID=666
$ MYFMT="${MYFMT} \n%s"
$ DATA_ARRAY+=("[Remove] \ID: $dataID Data missing -> Removing $dataID")
$ printf "${FMT}" "${DATA[@]}"
data1 data2 data3 data4 data5 data6 data7 data8
[Remove] \ID: 666 Data missing -> Removing 666
# to see what printf sees:
$ set -x
$ printf "${FMT}" "${DATA[@]}"
+ printf '\n%-5s %-10s %-15s %-10s %-5s %-5s %-5s %-120s \n%s' data1 data2 data3 data4 data5 data6 data7 data8 '[Remove] \ID: 666 Data missing -> Removing 666'
data1 data2 data3 data4 data5 data6 data7 data8
[Remove] \ID: 666 Data missing -> Removing 666
Upvotes: 0
Reputation: 123570
"${array[*]}"
will concatenate all elements into a single argument. "${array[@]}"
will expand to one argument per element:
$ args=("Hello %s\n" "World")
$ printf "${args[@]}"
Hello World
Upvotes: 2