如何使用内部 bash shell 为 docker exec 设置当前工作目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32343607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:31:46  来源:igfitidea点击:

How can I set the current working directory for docker exec with an internal bash shell?

bashdocker

提问by Matt

I have a developer docker image based on ubuntu:14.04 that I use to develop apps for Ubuntu 14.04. I start this image when the machine boots with docker start image-name

我有一个基于 ubuntu:14.04 的开发人员 docker 映像,我用它来为 Ubuntu 14.04 开发应用程序。当机器启动时我启动这个图像docker start image-name

My home directory was bind mounted with --volumes when initially created.

我的主目录在最初创建时绑定了 --volumes 。

To enter the image I have an alias defined in .bash_aliases

要输入图像,我定义了一个别名 .bash_aliases

alias d_enter="docker exec -ti ub1404-dev /bin/bash"

So to enter the image I just type d_enter

所以要输入图像,我只需输入 d_enter

But I often forget to run d_enter after entering a long path and would like d_enter to switch to that internal directory automatically.

但是我经常忘记在输入长路径后运行d_enter,并希望d_enter自动切换到该内部目录。

The following doesn't work.

以下不起作用。

docker exec -ti ub1404-dev /bin/bash <(echo ". ~/.bashrc && cd $(pwd)")

Is there another way I could achieve the desired result?

有没有另一种方法可以达到我想要的结果?

For example, if my current working directory is: /home/matt/dev/somepath/blabla

例如,如果我当前的工作目录是: /home/matt/dev/somepath/blabla

And I type d_enter, my current working directory currently becomes: /home/mattwhat I want to do for current directory after exec is be /home/matt/dev/somepath/blabla

然后我输入 d_enter,我当前的工作目录现在变成了:/home/matt我想在 exec 之后对当前目录做的事情是/home/matt/dev/somepath/blabla

采纳答案by Lucas Basquerotto

From API 1.35+ you can use the -w(--workdir) option:

从 API 1.35+ 开始,您可以使用-w( --workdir) 选项:

docker exec -w /my/dir container_name command

https://docs.docker.com/engine/reference/commandline/exec/

https://docs.docker.com/engine/reference/commandline/exec/

回答by Aung Kyaw Nyunt

You can achieve it with:
docker exec -it containerName sh -c "cd /var/www && /bin/bash"

您可以通过以下方式实现:
docker exec -it containerName sh -c "cd /var/www && /bin/bash"

回答by Peter Lyons

Definitely a hack but you could do something like making d_entera shell function (could stay an alias but this is easier to maintain):

绝对是一个 hack,但你可以做一些像制作d_entershell 函数的事情(可以保持别名,但这样更容易维护):

d_enter() {
  pwd > ~/.docker_initial_pwd
  docker exec -ti ub1404-dev /bin/bash
}

And then in the container in your user account's .bashrc, add something like:

然后在您的用户帐户的容器中.bashrc,添加如下内容:

if [[ -f "${HOME}/.docker_initial_pwd ]]; then
  cd $(cat "${HOME}/.docker_initial_pwd")
fi