大网数据广告活动
服务器运维问答

Why are environment variables different with `bash -c`

· 52CE 我爱测

How come the following, i.e. echoing $PATH directly from bash -c : docker exec -i -t my_container bash -c "echo $PATH" returns a different value for $PATH than what follows, i.e. starting an interactive bash session and echoing t…

问题原文

原帖链接 · Alessandro Vernet · CC BY-SA 3.0

How come the following, i.e. echoing $PATH directly from bash -c:

docker exec -i -t my_container bash -c "echo $PATH"

returns a different value for $PATH than what follows, i.e. starting an interactive bash session and echoing the $PATH?

docker exec -i -t my_container bash 
root@21e6d898c3c2:/# echo $PATH

To give some context to this question, I'd like to run a command in the container with docker exec, and this command is on the path if I start an interactive bash session, but isn't if I just run the command.

Using the full path of the executable isn't a workaround in this case, as the command relies on other environment variables that, just like PATH are set in a bash interactive session, but not if I run the command up straight.

已采纳解答

原帖链接 · chicks · CC BY-SA 3.0

When -c is specified bash is not running as interactive or a login shell so it won't read the same startup scripts. Anything set in /etc/profile, ~/.bash_profile, ~/.bash_login, or ~/.profile would definitely be skipped.

Also, as explained by the bash man page:

Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell daemon, usually rshd, or the secure shell daemon sshd. If bash determines it is being run in this fashion, it reads and executes commands from ~/.bashrc and ~/.bashrc, if these files exist and are readable.

So if it doesn't think you're connecting across the network it might not read the .bashrc file either which would skip everything not skipped by the previous step.

solution

To work around this issue I would create a script that sets the PATH to something suitable and then run the command. If you want to use the existing .profile or other files then you can just source it in your script.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-11-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。