yegor256
yegor256

Reputation: 105063

How to stay in the directory after subshell completion?

I'm trying to do this (just an example, not a real life situation):

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

However, it fails, since cd test directory change is reverted after subshell is finished. What is a workaround? I can't use script .sh files, everything should be in one command line.

Upvotes: 1

Views: 372

Answers (3)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45576

Skip the subshell and use a { ... } block instead (or explain your usecase, since this example does not make so much sense):

$ find
.
$ mkdir dir; { cd dir; echo foo > test.txt; }; cat test.txt
foo
$ cd ..
$ find
.
./dir
./dir/test.txt

Upvotes: 5

crw
crw

Reputation: 685

As commenters have said, a child process can't modify the parent's working directory. You can return a value from the child process for the parent to read, then make the parent act on this value. Meaningless bash example:-

$ mkdir test; DIR=$( cd test; echo "foo" > test.txt; echo test ); cat $DIR/test.txt

Upvotes: 1

konsolebox
konsolebox

Reputation: 75488

Why not just?

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

Another way is

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

Or

mkdir test; (cd test; echo "foo" > test.txt; echo "$PWD" > /some/file); cd "$(</some/file)"; cat test.txt

Upvotes: 3

Related Questions