Reputation: 27
I have the requirement to capture pod memory and other details in my setup. have written small reproducible shell script as copied below.
LOGFILE='/root/User1/test/log'
Data=""
space=" "
e=34
f=12Mi
a=122
b=123
c=333
d=450
for i in {1..10}; do
Data+=$space
Data+=$a
Data+=$space
Data+=$b
Data+=$space
Data+=$c
Data+=$space
Data+=$d
Data+=$space
Data+=$e
Data+=$space
Data+=$f
printf "%s" "$Data" >> ${LOGFILE}
echo $'\n' >> ${LOGFILE}
$(unset ${Data})
done
The above script produces concatenated output.
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450 34 12Mi 122 123 333 450
34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450
34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450
34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450
34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122 123 333 450 34 12Mi 122
The output format what I am looking for is
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
34 12Mi 122 123 333 450
can some one help me here to understand what mistake I am doing here. and what could be the possible solution for this.
Upvotes: 0
Views: 48
Reputation: 52316
When you do $(unset ${Data})
, you are running unset ${Data}
in a subshell, and then try to run its output (the empty string) as a command. This is wrong on a few levels:
unset
takes the name of the variable, not its expansion, as a parameterThe quick fix is to replace $(unset ${Data})
with unset Data
.
A simpler overall approach could be to skip the intermediate variable entirely, and move the redirection out of the loop:
for i in {1..10}; do
printf '%s ' "$e" "$f" "$a" "$b" "$c"
printf '%s\n\n' "$d"
done >> "$LOGFILE"
This doesn't require $Data
or $space
any longer.
This prints the exact desired output you show, though the actual output you show doesn't correspond to your script, which has each line begin with three blanks. To get that, the printf
formatting strings would have to be ' %s'
and ' %s\n\n'
, respectively.
Upvotes: 2