代码示例如下图所示,在while中变量namelist、image_hash无法传到循环外部。
原因:使用了管道的缘故,当启用管道时,会生成一个subshell,while循环的代码在subshell中执行
function generate_ota_package() { local namelist=$filelist" "$ota_hash_sig openssl sha -sha256 $filelist | awk '{print $2}' | head -c 64 > $filelist_hash reinit_file $filelist_hash cat $filelist | while read line do partition_name=`echo $line | awk '{print $1}'` image=`echo $line | awk '{print $2}'` if [[ $image == "" ]];then continue fi namelist=$namelist" "$image echo "============"$namelist image_hash=`openssl sha -sha256 $image | awk '{print $2}'` echo $partition_name" "$image" "$image_hash >> $filelist_hash done < $filelist echo $namelist echo $image_hash signature_ota tar cvzf $ota_name $namelist }
修改方案如下:
function generate_ota_package() { local namelist=$filelist" "$ota_hash_sig openssl sha -sha256 $filelist | awk '{print $2}' | head -c 64 > $filelist_hash reinit_file $filelist_hash while read line do partition_name=`echo $line | awk '{print $1}'` image=`echo $line | awk '{print $2}'` if [[ $image == "" ]];then continue fi namelist=$namelist" "$image echo "============"$namelist image_hash=`openssl sha -sha256 $image | awk '{print $2}'` echo $partition_name" "$image" "$image_hash >> $filelist_hash done < $filelist echo $namelist echo $image_hash signature_ota tar cvzf $ota_name $namelist }