当前位置: 动力学知识库 > 问答 > 编程问答 >

shell - Reusing variables in bash

问题描述:

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.

网友答案:

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.

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: