想着定义个全局变量,用sh 函数修改,结果遇到了管道的坑,先贴错误代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #!/bin/sh
HEIGHT="null" WIDTH="default" SRC_YUV= DEST_DIR= MAX_QP= MIN_QP=
read_para_from_file(){ cat $1 | while read line ##划重点--->管道的最后一个命令都是在子Shell中执行的。这意味着在子Shell中赋值的变量对父Shell是无效的。所以当我们将管道输出传送到一个循环结构,填入随后将要使用的变量,那么就会产生很多问题。一旦循环完成,其所依赖的变量就不存在了。 do echo $line t_name=`echo $line |awk -F ' ' '{print $1}'` t_value=`echo $line |awk -F ' ' '{print $2}'` echo "k-v :$t_name -> $t_value" if [ $t_name = "width" ] ; then echo "1 ->"$WIDTH WIDTH=$t_value echo "1 ->"$WIDTH continue fi if [ $t_name = "height" ] ; then echo "2 ->"$HEIGHT HEIGHT=$t_value echo "2 ->"$HEIGHT continue fi if [ $t_name = "src_yuv" ] ; then SRC_YUV=$t_value echo "3 ->"$SRC_YUV continue fi if [ $t_name = "dest_dir" ] ; then DEST_DIR=$t_value echo "4" continue fi if [ $t_name = "max_qp" ] ; then MIN_QP=$t_value echo "5" continue fi if [ $t_name = "min_qp" ] ; then MAX_QP=$t_value echo "6" continue fi echo "get nothing -> "$line done } show_global_para(){ echo "show global var ->" echo "WIDTH -> $WIDTH" echo "HEIGHT -> $HEIGHT" echo "SRC_YUV -> $SRC_YUV" echo "DEST_DIR -> $DEST_DIR" echo "MAX_QP -> $MAX_QP" echo "MIN_QP -> $MIN_QP" }
read_para_from_file $1 show_global_para
|
1
| 管道的最后一个命令都是在子Shell中执行的。这意味着在子Shell中赋值的变量对父Shell是无效的。所以当我们将管道输出传送到一个循环结构,填入随后将要使用的变量,那么就会产生很多问题。一旦循环完成,其所依赖的变量就不存在了。
|
修改后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #!/bin/sh
HEIGHT="null" WIDTH="default" SRC_YUV= DEST_DIR= MAX_QP= MIN_QP=
read_para_from_file(){ #cat $1 | while read line #lines=`cat $1` while read line ##划重点 do echo $line t_name=`echo $line |awk -F ' ' '{print $1}'` t_value=`echo $line |awk -F ' ' '{print $2}'` echo "k-v :$t_name -> $t_value" if [ $t_name = "width" ] ; then echo "1 ->"$WIDTH WIDTH=$t_value echo "1 ->"$WIDTH continue fi if [ $t_name = "height" ] ; then echo "2 ->"$HEIGHT HEIGHT=$t_value echo "2 ->"$HEIGHT continue fi if [ $t_name = "src_yuv" ] ; then SRC_YUV=$t_value echo "3 ->"$SRC_YUV continue fi if [ $t_name = "dest_dir" ] ; then DEST_DIR=$t_value echo "4" continue fi if [ $t_name = "max_qp" ] ; then MIN_QP=$t_value echo "5" continue fi if [ $t_name = "min_qp" ] ; then MAX_QP=$t_value echo "6" continue fi echo "get nothing -> "$line done < $1 ##重定向 } show_global_para(){ echo "show global var ->" echo "WIDTH -> $WIDTH" echo "HEIGHT -> $HEIGHT" echo "SRC_YUV -> $SRC_YUV" echo "DEST_DIR -> $DEST_DIR" echo "MAX_QP -> $MAX_QP" echo "MIN_QP -> $MIN_QP" }
read_para_from_file $1 show_global_para
|