4

The folder structure like this:

folder_01
├── folder_02├──Dockerfile_02
├── folder_03├──Dockerfile_03 & example.sh

In the example.sh script, I want to use cd to navigate back to folder_02 and use the dockerfile_02 to build an image and then navigate back to the current dir (which is folder_03) Here's what I tried:

cd ..
cd ./folder_02
docker build . -t image_name

cd ..
cd ./folder_03

In intelliJ, it gave me warning using a subshell to avoid having to cd back, I read some documentation about it but haven't got a solution, can someone help me?

wawawa
  • 2,835
  • 6
  • 44
  • 105
  • Did you ask the same question twice? [how to resolve warning ''using a subshell to avoid having to cd back'](https://stackoverflow.com/q/61956289/3776858) – Cyrus May 22 '20 at 13:47
  • @Cyrus Thanks for letting me know, must be the bad network connection and I submitted twice accidentally. I've deleted the other one. – wawawa May 22 '20 at 14:24

2 Answers2

12

You can invoke the commands in a subshell (...):

(
   cd ./folder_02
   docker build . -t image_name
)
(
   cd ./folder_03
   something else
)

In scripts that I want to preserve environment I use pushd+popd.

pushd ./folder_02 >/dev/null
docker build . -t image_name
popd >/dev/null

pushd ./folder_03 >/dev/null
something soemthing
popd >/dev/null
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • As per the question post, the PWD is folder_03. I supppose this answer has to be changed for that. – Fazlin May 22 '20 at 13:45
  • i know how `pushed`, `popd` and `dir` works, but what do you mean in to preserve the environment? – Mahmoud Odeh May 22 '20 at 14:43
  • `a=1; ( a=2; ); echo "$a"` will print `1`, because changes in subshell are not visible in parent shell. By "preserve environment" I meant that the environment of the `(...)` part is lost, and I want to keep using it in the script. Well, it's not the best term... – KamilCuk May 22 '20 at 14:44
  • Note that `pushd` and `popd` are bash extensions, but `(cd dir; command)` is portable POSIX shell syntax. In a Docker context this may make a difference, where lighter-weight Alpine-based images may not have bash available. – David Maze May 22 '20 at 21:13
1

you can use subshell (...) like what @KamilCuk said

(cd ../folder_02 && docker build . -t image_name )
(cd ../folder_03 && something else)

or

(cd ../folder_02; docker build . -t image_name )
(cd ../folder_03; something else)

Since with Docker, you can use the -f argument to select the Dockerfile to use :

docker build -t path/yourproject -f dockerfiles/myownDocker.docker .
Mahmoud Odeh
  • 942
  • 1
  • 7
  • 19