Node.js中.env变量特殊字符转义问题:git clone密码丢失&7
问题描述
我的.env文件包含两个变量:
USERNAME="myusername" PASSWORD="mypassword&7"
执行以下Node.js代码调用shell.exec执行git clone时,密码中的&7部分被忽略:
shell.exec(`git clone https://${process.env.USERNAME}:${process.env.PASSWORD}@github.com/my-repo/xyz-git-ops.git`);
得到错误输出:
/bin/sh: 7@gmy-repo/xyz-git-ops.git: No such file or directory
Cloning into 'mypassword'...
fatal: unable to access 'https://myusername:mypassword/': URL using bad/illegal format or missing URL
发现两个异常:
- 密码末尾的
&7被忽略,git clone输出中替换为/; - 用
console.log(process.env.PASSWORD)能正常输出完整密码mypassword&7。
完整代码如下:
const nodeCron = require("node-cron"); const shell = require('shelljs'); const rpath = '/Users/myuser/Documents/Git Ops Cron/repos'; require('dotenv').config(); const start = Date.now(); const username = process.env.USERNAME const password = process.env.PASSWORD async function xyzGitOps(){ console.log("Running scheduled job", start); shell.cd(rpath); shell.exec(`git clone https://${username}:${password}@github.com/my-repo/xyz-git-ops.git`); return console.log("Job finished"); } const job = nodeCron.schedule("* * * * *", xyzGitOps);
问题原因
&是Shell中的特殊字符,代表将命令放到后台执行。当用模板字符串拼接命令时,Shell会把mypassword&7中的&解析为命令分隔符,将mypassword当作前半部分命令的结尾,7@github.com/...被当作新的命令执行,这就导致密码被截断,URL格式错误。
解决方案
有两种可靠的解决方式:
方式一:对密码进行URL编码
URL中的特殊字符需要转义,&对应的URL编码是%26。可以用Node.js的encodeURIComponent方法对密码进行编码:
const encodedPassword = encodeURIComponent(password); shell.exec(`git clone https://${username}:${encodedPassword}@github.com/my-repo/xyz-git-ops.git`);
方式二:使用命令数组形式调用shell.exec
shell.exec支持传入命令数组,这种方式会绕过Shell解析,直接执行命令,避免特殊字符被误解析:
shell.exec(['git', 'clone', `https://${username}:${password}@github.com/my-repo/xyz-git-ops.git`]);
注:你原来的代码里存在笔误,将process.env.PASSWORD误写为process.env.USERNAME,上述示例已修正该问题。
内容的提问来源于stack exchange,提问作者c0d3rbox
相关产品推荐
相关产品推荐

