1

我正在尝试这样做(只是一个例子,不是现实生活中的情况):

$ mkdir test; ( cd test; echo "foo" > test.txt ); cat test.txt
cat: test.txt: No such file or directory

但是,它失败了,因为cd test在 subshel​​l 完成后目录更改被恢复。什么是解决方法?我不能使用脚本.sh文件,一切都应该在一个命令行中。

4

3 回答 3

5

跳过子外壳并改用{ ... }块(或解释您的用例,因为此示例没有多大意义):

$ find
.
$ mkdir dir; { cd dir; echo foo > test.txt; }; cat test.txt
foo
$ cd ..
$ find
.
./dir
./dir/test.txt
于 2013-08-29T13:32:36.990 回答
3

为什么不只是?

mkdir test; echo "foo" > test/test.txt; cat test/test.txt

另一种方法是

mkdir test; cd "$(cd test; echo "foo" > test.txt; echo "$PWD";)"; cat test.txt

或者

mkdir test; (cd test; echo "foo" > test.txt; echo "$PWD" > /some/file); cd "$(</some/file)"; cat test.txt
于 2013-08-29T13:17:01.857 回答
1

正如评论者所说,子进程不能修改父进程的工作目录。您可以从子进程返回一个值供父进程读取,然后让父进程对该值进行操作。无意义的bash例子:-

$ mkdir test; DIR=$( cd test; echo "foo" > test.txt; echo test ); cat $DIR/test.txt
于 2013-08-29T13:20:36.037 回答