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

Cron执行Shell脚本时移除环境变量中$字符的问题排查

Cron执行脚本丢失环境变量中$符号的解决方案

问题背景

Docker容器内的密码环境变量包含$符号,手动运行Shell脚本可正常输出完整密码,但Cron执行时,$及其后两个字符会被移除(例如blahblah$xy*blahblah变为blahblah*blahblah)。原脚本和Cron配置如下:

原脚本(testVars.sh)

#!/bin/bash

echo "Testing variables"

MY_PASS=$MY_PASSWORD
TEST_PASS=$(sed -e 's/[^a-zA-Z0-9,._+@%/-]/\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/' <<< $MY_PASSWORD)

echo ${MY_PASS}
echo ${TEST_PASS}

原Cron配置

BASH_ENV=/root/env_vars.sh
33 13 * * * root /opt/testVars.sh >> /opt/cron.log

修复步骤

1. 环境变量文件中用单引号包裹密码

在/root/env_vars.sh里,给含$的密码变量添加单引号,避免Cron将$解析为变量引用:

export MY_PASSWORD='blahblah$xy*blahblah'

注意:必须用单引号,双引号仍会触发Shell对$xy的解析(若该变量未定义则为空)。

2. 脚本中变量引用添加双引号

脚本内所有引用$MY_PASSWORD的位置都要加双引号,防止Shell分词和特殊字符解析:
修改后的testVars.sh:

#!/bin/bash

echo "Testing variables"

MY_PASS="$MY_PASSWORD"
TEST_PASS=$(sed -e 's/[^a-zA-Z0-9,._+@%/-]/\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/' <<< "$MY_PASSWORD")

echo "${MY_PASS}"
echo "${TEST_PASS}"

3. 验证Cron环境加载

确保/root/env_vars.sh权限为root可读(如执行chmod 600 /root/env_vars.sh),且每个export命令单独一行,无语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:35:23