I want to know if reusing the same set of variables can lead to any unforeseen events in a bash script .Is it generally regarded as a good practice ?
To make my query a bit more clearer.
I have a script which goes like this :
max=`cat loc1.c | wc -l`
bar=1
while [ $bar -lt $max ]
do
f1=`awk -v vr1=$bar 'NR == vr1' loc1.c`
f2=`awk -v vr1=$bar 'NR == vr1' loc2.c`
if [[ a random file exists ]] ; then # use var1 var2 var3 ; fi
if [[ a random file2 exists ]] ; then # use var1 var2 var3 ; fi
if [[ a random file3 exists ]] ; then # use var1 var2 var3 ; fi
((bar++))
done
The files loc1 and loc2 lists file paths separated by newlines . The paths are transferred with respect to the line numbers to the variables f1 and f2 . The loop continues until each file (pointed by the path) in loc1 has done some kind of data manupulation with files pointed in loc2.
Any kind of suggestions are welcome .
I am reusing the variables var1,var2 ,var3 [..] in the code that follows.
Not related to variable use, but you can simplify your file iteration, assuming you don't need bar or max for anything else:
while read -r f1 && read -r -u 3 f2; do
if [[ a random file exists ]] ; then # use var1 var2 var3 ; fi
if [[ a random file2 exists ]] ; then # use var1 var2 var3 ; fi
if [[ a random file3 exists ]] ; then # use var1 var2 var3 ; fi
done < loc1.c 3< loc2.c
The only issue with reused variables is whether they are initialized appropriately at each point in the script where they are used. If each paragraph always sets the value before using it, there's no harm in the reuse. The main guideline should be clarity of the code. If the code is clear, then there's no problem.
Once upon a long time ago, one might have argued that variable reuse saved memory; these days, I wouldn't bother with the claim.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With