现在的位置: 首页 > 综合 > 正文

subshell/子shell问题总结

2013年10月17日 ⁄ 综合 ⁄ 共 2324字 ⁄ 字号 评论关闭

近来编写一个shell脚本,碰到一个变量作用域的问题,调试良久无果,查找相关资料才知道是子shell的问题。子shell的情况在shell当中还是比较普遍的,特此总结,以防再犯类似错误。

1、问题由来

n=0
ls | while read -r line
do
    n=$((n+1))
done
echo "total number of files: $n"

变量n在while循环里被计算赋值,但是最后echo出的值还是0。

问题在于管道,这里通过管道给while循环输入参数,bash将启动子shell运行while循环,子shell继承父shell的变量,但是子shell对变量的任何操作都不会影响父shell。


2、子shell定义

参考:《Bash Reference Manual》

http://tiswww.case.edu/php/chet/bash/bashref.html#SEC60

 a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands
that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell's execution environment.

子shell复制了父shell的运行环境,除了traps初始化为父shell的初始状态。子shell对shell运行环境的改变不会影响父shell。


3、shell的运行环境

shell的运行环境包括:

  • open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin

  • the current working directory as set by cdpushd, or popd, or inherited by the shell at invocation

  • the file creation mode mask as set by umask or inherited from the shell's parent

  • current traps set by trap

  • shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment

  • shell functions defined during execution or inherited from the shell's parent in the environment

  • options enabled at invocation (either by default or with command-line arguments) or by set

  • options enabled by shopt

  • shell aliases defined with alias

  • various process IDs, including those of background jobs , the value of $$, and the value of $PPID

子shell的运行环境包括:

When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited
from the shell.

  • the shell's open files, plus any modifications and additions specified by redirections to the command

  • the current working directory

  • the file creation mode mask

  • shell variables and functions marked for export, along with variables exported for the command, passed in the environment (see section 3.7.4 Environment)

  • traps caught by the shell are reset to the values inherited from the shell's parent, and traps ignored by the shell are ignored
A command invoked in this separate environment cannot affect the shell's execution environment.

4、子shell发生情况

命令替换:``,$()

a=1
b=`echo ${1}`
c=`a=2;echo ${1}`
echo "a=${a},b=${b},c=${c}"
//结果为:a=1,b=1,c=2

圆括号

a=1
(
echo "shell_1=${a}"
)
(
a=2
echo "shell_2=${a}"
)
echo "a=${a}"
//结果为:
//shell_1=1
//shell_2=2
//a=1

管道:

如“1、问题由来”


抱歉!评论已关闭.