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

Azure Pipeline执行Bash脚本时字符串比较始终返回false问题

问题描述

本地执行正常的字符串比较脚本,在Azure Pipeline通过az vm run-command invoke调用时,if语句始终进入else分支。

示例脚本(script.sh):

#############################################
teststr="test"
echo $teststr
if [[ $teststr == "test" ]]; then
      echo "true"
else
      echo "false"
fi
    
if [[ $teststr != "test" ]]; then
      echo "true"
else
      echo "false"
fi
#############################################

预期输出:

test
true
false

Azure Pipeline中执行的命令:

az vm run-command invoke --command-id RunShellScript --name MyVM -g Takeoffs --scripts "cd /home/user/workdir/ && 
    ./script.sh" 

实际输出:

test
false
false

尝试过比较不同字符串、添加引号、使用-eq/-ne运算符,均无效,怀疑是环境差异导致。

解决方案

问题根源是远程VM的默认执行shell可能不是Bash,而是POSIX兼容的sh。[[ ]]是Bash的扩展语法,sh不支持这种写法,导致比较逻辑失效。

以下是三种可行的解决方式:

1. 为脚本添加Bash shebang头

在script.sh的最开头添加指定解释器的声明,确保脚本强制用Bash执行:

#!/bin/bash
#############################################
teststr="test"
echo $teststr
if [[ $teststr == "test" ]]; then
      echo "true"
else
      echo "false"
fi
    
if [[ $teststr != "test" ]]; then
      echo "true"
else
      echo "false"
fi
#############################################

2. 调用脚本时指定Bash解释器

修改az vm run-command invoke的--scripts参数,明确用bash执行脚本:

az vm run-command invoke --command-id RunShellScript --name MyVM -g Takeoffs --scripts "cd /home/user/workdir/ && bash ./script.sh"

3. 修改比较语法兼容POSIX sh

将Bash专属的[[ ]]替换为POSIX标准的[ ],同时注意运算符和引号的规范([是命令,前后需要空格;字符串比较用=而非==;变量加引号防止空值异常):

#############################################
teststr="test"
echo $teststr
if [ "$teststr" = "test" ]; then
      echo "true"
else
      echo "false"
fi
    
if [ "$teststr" != "test" ]; then
      echo "true"
else
      echo "false"
fi
#############################################

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:55:04