Chinaunix

标题: ()中打印的PID值为啥和()外打印的值一样啊? [打印本页]

作者: good_luck_68    时间: 2013-03-13 14:09
标题: ()中打印的PID值为啥和()外打印的值一样啊?

脚本内容:
#!/bin/bash
echo "out PID=$$"
a=10
echo $a
(
echo "in PID=$$"
a=5
echo $a
)
echo $a


AAA:/home/test # ./111
out PID=11029
10
in PID=11029
5
10


疑问:()内的命令不是在子shell中执行的吗,为啥查询的PID值和括号外的相同?
作者: llh580110    时间: 2013-03-13 14:34
(...)结构
小括号内的命令会在一个子shell环境中执行,命令执行的结果不会影响当前的shell环境。需要注意是此时变量$$会显示当前shell的进程id,而不是子shell的进程id。

作者: waker    时间: 2013-03-13 14:49
[ 本帖最后由 waker 于 2013-03-13 14:50 编辑 ]

[code]
echo '$$ in current shell is ' $$
( cd /proc/self/task
echo -n 'Pid of nested subshell is '
ls
echo '$$ in nested shell is ' $$)
[/code]
作者: good_luck_68    时间: 2013-03-13 16:36
回复 3# waker


根据您给的代码执行了一下提示错误,实在没看明白哪块错误

AA:/home/test # cat 5
echo '$$ in current shell is ' $$
( cd /proc/self/task
echo -n 'Pid of nested subshell is '
ls
echo '$$ in nested shell is ' $$)

AA:/home/test # ./5
$$ in current shell is  12837
'/5: line 5: syntax error near unexpected token `
'/5: line 5: `echo '$$ in nested shell is ' $$)

作者: waker    时间: 2013-03-13 16:44
请用bash
作者: good_luck_68    时间: 2013-03-13 17:15
回复 5# waker

AA:/home/test # cat 5
#!/bin/bash

echo '$$ in current shell is ' $$
( cd /proc/
echo -n 'Pid of nested subshell is '
ls
echo '$$ in nested shell is ' $$)

AA:/home/test # ./5
-bash: ./5: /bin/bash^M: bad interpreter: No such file or directory


加上“#!/bin/bash”之后就变成这个错误了。。。确实有/proc这个目录,直接执行cd也成功

   
作者: Shell_HAT    时间: 2013-03-13 17:33
回复 6# good_luck_68
  1. dos2unix 5
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2