You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL中bash.exe执行脚本不加载.bashrc,如何实现加载后运行脚本?

问题:让bash执行脚本时先加载.bashrc的方法

我在Windows 11的WSL2 Ubuntu 20.04环境下,给~/.bashrc添加了一行内容:

echo ".bashrc executed"

在CMD命令提示符中创建test.sh文件,内容如下:

#!/bin/bash
echo "Test"

执行命令bash.exe test.sh时,仅输出:

Test

但我预期的输出是:

.bashrc executed
Test

而直接执行bash.exe进入交互式shell时,能正常输出.bashrc executed。请问如何运行bash,使其先加载.bashrc再执行test.sh?


解决方法

bash在执行脚本时默认是非交互式非登录shell,这种模式下不会自动加载.bashrc,可以通过以下几种方式实现需求:

方法1:使用交互式shell参数-i

执行命令时加上-i参数,强制bash以交互式模式运行,这时会自动加载.bashrc:

C:\Users\andy> bash.exe -i test.sh

方法2:手动在脚本中source .bashrc

修改test.sh,在开头添加加载.bashrc的命令:

#!/bin/bash
source ~/.bashrc
echo "Test"

修改后直接执行bash.exe test.sh即可。

方法3:用--rcfile指定加载.bashrc

执行命令时通过--rcfile参数明确指定加载.bashrc:

C:\Users\andy> bash.exe --rcfile ~/.bashrc test.sh

内容的提问来源于stack exchange,提问作者andynewman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:20:06