V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
atom
V2EX  ›  Linux

一个复制目录的命令组合,为什么工作目录没有变?

  •  
  •   atom · 2012-12-11 11:28:32 +08:00 · 3525 次点击
    这是一个创建于 4147 天前的主题,其中的信息可能已经有所发展或是发生改变。
    读 jar 的 manual 的时候,发现一个复制目录的有趣命令
    (cd dir1; jar c .) | (cd dir2; jar x)
    它进入到目录 dir1 ,打包所有文件到标准输出,通过管道传递,在目录 dir2 中,从标准输入解压文件。

    我不明白的是,为什么执行命令前后,工作目录(pwd)会没有变?
    比如,cd 到 dir1 后,为什么不用先 cd ../dir2 ?

    7 条回复    1970-01-01 08:00:00 +08:00
    yegle
        1
    yegle  
       2012-12-11 13:19:48 +08:00   ❤️ 1
    每个管道都是一个新的子shell,除非在父进程修改了pwd,一个子shell是不能修改另一个子shell的pwd的

    课后题:为什么这段代码里第一部分无法正常工作?
    https://gist.github.com/4256080
    tmtsrc46
        2
    tmtsrc46  
       2012-12-11 13:26:11 +08:00   ❤️ 1
    因为在shell中圆括号"()"创建了子进程。
    cd dir1; jar c .
    这句是在子进程里进行的,执行到")"的时候会结束掉子进程,你当前这个进程的shell的PWD是没变的。
    你可以试试这两个语句的区别:
    (cd dir1; ls)
    cd dir1; ls
    bitsmix
        3
    bitsmix  
       2012-12-11 14:08:32 +08:00
    @yegle 呃。。。我怎么都正常工作呢呀。 bash / zsh 都是这样
    atom
        4
    atom  
    OP
       2012-12-12 13:49:25 +08:00
    @yegle 课后题可以解释下吗?
    为什么把echo 改为 cat就可以呢?

    abs-book里面有提到read读取管道的问题,但对于cat为什么可以,好像没有一个清晰的解释。或者是我理解力不够。

    Example 15-8. Problems reading from a pipe
    http://tldp.org/LDP/abs/html/internal.html

    http://tldp.org/LDP/abs/html/gotchas.html#BADREAD0
    yegle
        5
    yegle  
       2012-12-12 15:10:46 +08:00
    @bitsmix
    @atom
    我写代码时绝对抽风了…已经修改gist…
    atom
        6
    atom  
    OP
       2012-12-13 14:49:42 +08:00
    @yegle
    我还是不明白这里的trick是为什么
    ”Piping output to a read, using echo to set variables will fail.
    Yet, piping the output of cat seems to work.“
    http://tldp.org/LDP/abs/html/internal.html
    yegle
        7
    yegle  
       2012-12-14 14:54:40 +08:00
    @atom 管道符号后的部分是另一个子shell,read是能读到内容然后存入变量。但是随后这个shell就结束了,在父shell里读不到这个变量
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1567 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:52 · PVG 00:52 · LAX 09:52 · JFK 12:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.