Bash脚本数组比较问题

Bash脚本数组比较问题,bash,Bash,我的脚本中有以下代码: RESULT=$(cora_cmd --input={connect hrdwtst01.campbellsci.com';' file-control $STATION_NAME stop-program';' bye';'}) declare y IFS=$'\n' y=($RESULT) echo ${y[2]} if [ ${y[2]} == '-file-control,loggernet datalogger locked' ]; then echo

我的脚本中有以下代码:

RESULT=$(cora_cmd --input={connect hrdwtst01.campbellsci.com';' file-control $STATION_NAME stop-program';' bye';'})
declare y
IFS=$'\n' y=($RESULT)
echo ${y[2]}
if [ ${y[2]} == '-file-control,loggernet datalogger locked' ]; then
    echo -e "\t\E[31;1m.. ERROR - Not able to stop the datalogger's program. ..\E[37;0m"
fi
echo "$RESULT"
比较不起作用,它从不进入if语句。有什么想法吗

集合-x的结果:

'++ cora_cmd '--input={connect' 'hrdwtst01.campbellsci.com;' file-control TS_CR850_PB_801 'stop-program;' 'bye;}'
+ RESULT='CoraScript 1, 13, 06 Beta
+connect,"coralib3.dll version 1, 7, 18 Beta"
'file-control,loggernet datalogger locked
+ declare y
+ IFS='
'
+ y=($RESULT)
' echo '-file-control,loggernet datalogger locked
-file-control,loggernet datalogger locked
' '!=' '-file-control,loggernet datalogger locked' ']'
+ echo -e '\t\E[31;1m.. ERROR - Not able to stop the datalogger'\''s program.   ..\E[37;0m'
    .. ERROR - Not able to stop the datalogger's program. ..'

始终引用变量,除非您知道希望在扩展上执行分词和全局搜索

if [ "${y[2]}" = '-file-control,loggernet datalogger locked' ]; then
您还可以使用内置的[[语法],它不会对变量进行单词拆分

if [[ ${y[2]} = '-file-control,loggernet datalogger locked' ]]; then
这里有一个杂散的^M,表示您的cora\u cmd输出 包括DOS样式的\r\n行结尾,您只需剥离 \n,保留回车符。这就是为什么不使用回车符的原因 找到一根火柴…-特瓦尔伯格

twalberg正确地诊断了问题。简单的解决方案当然是在IFS中包含\r:


在test=$'-文件控件中包含\r,loggernet datalogger locked\r'也是可能的。

脚本中的整个内容是否确实有反标记,或者这是您不正确的标记方式?没有。这只是stackoverflow的添加。请尝试用类似echo${y[2]}的内容替换第一个回音行| cat-vet检查您不希望出现的其他字符。特别是,由于您使用IFS的方式,您可能会在数组项上附加其他空白…-文件控制,loggernet数据记录器锁定^M$,因此那里有一个错误^M,指示您的cora_cmd输出包括DOS样式的\r\n行结尾,并且您只需要去掉\n,留下回车符。这就是为什么没有匹配的原因…谢谢。我已经尝试了这两种方法,但都不起作用。可能变量的开头或结尾有空格?echo |${y[2]}|show?将set-x放在脚本的开头,这样它会在运行时显示所有变量已展开的命令。谢谢Barmer。set-x非常方便!将它放在问题中的代码块中,以便保留格式。
IFS=$'\r\n' y=($RESULT)