我正在尝试这样做(只是一个例子,不是现实生活中的情况):
$ mkdir test; ( cd test; echo "foo" > test.txt ); cat test.txt
cat: test.txt: No such file or directory
但是,它失败了,因为cd test
在 subshell 完成后目录更改被恢复。什么是解决方法?我不能使用脚本.sh
文件,一切都应该在一个命令行中。
跳过子外壳并改用{ ... }
块(或解释您的用例,因为此示例没有多大意义):
$ find
.
$ mkdir dir; { cd dir; echo foo > test.txt; }; cat test.txt
foo
$ cd ..
$ find
.
./dir
./dir/test.txt
为什么不只是?
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
正如评论者所说,子进程不能修改父进程的工作目录。您可以从子进程返回一个值供父进程读取,然后让父进程对该值进行操作。无意义的bash
例子:-
$ mkdir test; DIR=$( cd test; echo "foo" > test.txt; echo test ); cat $DIR/test.txt