我用命令行参数运行文件:
samplebash.bsh fakeusername fakepassword&123
.bsh文件:
echo "Beginning script..."
argUsername='$1'
argPassword='$2'
protractor indv.js --params.login.username=$argUsername --params.login.password=$argPassword
Run Code Online (Sandbox Code Playgroud)
输出:
开始脚本......
123:找不到命令
问题:出于某种原因,它将密码中的&符号作为命令解释,如何避免这种情况?
您的脚本中没有发生此问题,它发生在您的原始命令行中.&是一个命令终止符,它指定它之前的命令应该在后台执行.所以你的命令相当于:
samplebash.bsh fakeusername fakepassword &
123
Run Code Online (Sandbox Code Playgroud)
您需要引用参数以防止shell解释特殊字符.
samplebash.bsh fakeusername 'fakepassword&123'
Run Code Online (Sandbox Code Playgroud)
此外,您不应像在分配中那样在变量周围放置单引号,以防止变量被扩展.所以它应该是:
argUsername=$1
argPassword=$2
Run Code Online (Sandbox Code Playgroud)
在命令中使用变量时,应该在变量周围加上双引号,以防止解释通配符和空格.
protractor indv.js --params.login.username="$argUsername" --params.login.password="$argPassword"
Run Code Online (Sandbox Code Playgroud)
作为一般规则,除非您知道不需要,否则应始终在变量周围加上双引号.