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

使用AWS SSM执行EC2实例脚本时找不到依赖文件的问题求助

解决SSM执行脚本找不到依赖文件的问题

问题根源是AWS SSM的AWS-RunShellScript文档中,commands数组内的每条命令都是在独立子Shell进程中执行的。你写的cd ~/只会切换第一个子Shell的工作目录,后续的bash test_batch.sh是在全新Shell中运行,当前目录并非用户主目录,所以test_batch.sh里的./hello_world.sh找不到同目录下的文件。

下面是三种可行的解决办法:

方法1:合并命令到同一Shell执行

把切换目录和执行脚本的命令合并成一行,确保在同一个Shell进程中完成,这样工作目录的切换会生效:

aws ssm send-command \
    --document-name "AWS-RunShellScript" \
    --targets Key=tag:Name,Values=test-dev \
    --parameters '{"commands":["cd ~/ && bash test_batch.sh"]}' \
    --output text

方法2:在脚本中使用绝对路径调用依赖文件

修改test_batch.sh,将./hello_world.sh替换为绝对路径,这样无论当前执行目录是什么,都能定位到文件:

#!/bin/bash

echo "run hello world"
~/hello_world.sh

之后原SSM命令即可正常执行。

方法3:让脚本自适应执行路径

修改test_batch.sh,通过脚本自身路径来定位同目录下的hello_world.sh,这种方式最灵活,即使后续脚本被移动位置也能正常运行:

#!/bin/bash

echo "run hello world"
"$(dirname "$0")/hello_world.sh"

同时简化SSM命令,直接通过绝对路径调用脚本:

aws ssm send-command \
    --document-name "AWS-RunShellScript" \
    --targets Key=tag:Name,Values=test-dev \
    --parameters '{"commands":["bash ~/test_batch.sh"]}' \
    --output text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:32:20