arrays - Why is my bash shell script working on v 3.2.5 and failing on 4.1.2? -
my bash shell script working on bash 3.2.5. have input file contains following content:
1234567 2345678 3456789 4567890
and bash shell script has following code:
#!/bin/bash content=($(cat data.txt | awk {'print $1'})) (( i=0 ; i<${#content[@]} ; i++ )) if (( i==0 )) ele=`echo ${content[$i]}` else ele=`echo ","${content[$i]}` fi all=`echo $all$ele` done # should string of csv: works on bash 3.2.5 - fails on bash 4.1.2 echo $all
when run bash 3.2.5 outputs: (expected output; correct)
1234567,2345678,3456789,4567890
but when run bash 4.1.2 outputs: (the last number in file; not correct)
,4567890
why same code failing in bash 4.1.2?
using echo
set contents of variable plain .. wrong. when wrong, mean, can it, there absolutely no reason use command substitution
of echo
statement fill variables in case. likewise, there no reason use cat
piped awk
fill array. filling array easier done simple redirection.
by eliminating unneeded command substitution
of echo
, piped
commands, eliminate lot of opportunity error. here update work on either 3 or 4.
#!/bin/bash content=( $( <data.txt) ) (( i=0 ; i<${#content[@]} ; i++ )) if (( i==0 )) ele="${content[i]}" else ele=",${content[i]}" fi all="${all}${ele}" done echo $all
output
$ bash bash34fail.sh 1234567,2345678,3456789,4567890
Comments
Post a Comment