Alpine Linux中ash对应bashrc的配置文件是什么?
问题描述
我了解登录时会执行/etc/profile.d/*.sh脚本,但直接启动shell时该脚本未按预期生效。以下是Docker环境下的示例:
- 创建测试脚本:
$ echo "echo hello world" > startup.sh
- 将脚本挂载到Alpine容器并启动shell:
$ docker run -it --rm -v `pwd`/startup.sh:/etc/profile.d/statup.sh alpine sh
此时仅显示shell提示符:
/ #
- 执行
su -时会打印"hello world":
/ # su - hello world 2bf679a5677d:~#
- 直接执行
sh启动shell无此效果:
/ # sh / #
请问问题出在哪里?是Alpine Linux的特殊机制,还是其Docker镜像的特有问题?
问题原因与解决方案
这既不是Alpine的特殊机制,也不是Docker镜像的特有问题,核心是shell的启动模式差异:
- 登录shell(Login Shell):像
su -这种方式启动的shell属于登录shell,它会加载/etc/profile,而Alpine的/etc/profile里明确有遍历执行/etc/profile.d/*.sh脚本的逻辑,所以测试脚本会被执行,打印出hello world。 - 交互式非登录shell(Interactive Non-login Shell):直接用
sh或者容器启动时的sh属于这类shell,它不会加载/etc/profile,自然也不会执行/etc/profile.d下的脚本。
另外你挂载脚本时还犯了个小错误:把startup.sh写成了statup.sh,不过这不影响su -的测试场景,因为su -会遍历所有*.sh,只要文件名后缀正确就会执行。
如果想让交互式非登录shell也加载这些脚本,可以:
- 在
~/.profile里手动添加执行/etc/profile.d/*.sh的逻辑; - 启动shell时加上
-l参数(强制以登录shell模式启动),比如docker run -it --rm -vpwd/startup.sh:/etc/profile.d/startup.sh alpine sh -l,这样启动后直接就能看到hello world。
内容的提问来源于stack exchange,提问作者AlexanderF
相关产品推荐
相关产品推荐

