2026AI论文写作软件推荐
2026/6/6 19:23:59
在编写Bash脚本时,有时会遇到变量值异常的情况,例如$COUNT始终为零。这是因为管道会创建子shell,而while循环在子shell中运行,其内部对变量的更改不会影响脚本外部的变量。
COUNT=0 while read PREFIX GUTS do # ... if [[ $PREFIX == "abc" ]] then let COUNT++ fi # ... done < $1 # <<<< This is the key line echo "$COUNT now lives in the main script"while循环的子shell中。示例代码如下:COUNT=0 cat $1 | ( while read PREFIX GUTS do # ...