系统相关
首页 > 系统相关> > linux shell变量while循环内改变无法传递到循环外

linux shell变量while循环内改变无法传递到循环外

作者:互联网

代码示例如下图所示,在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
}

标签:namelist,shell,hash,image,filelist,echo,while,循环,print
来源: https://blog.51cto.com/u_15278218/2931156