首页 > 解决方案 > 检查保存在列表中的给定数字是否与条件匹配并在 shell 中打印相应的输出

问题描述

假设保存在变量中的数字列表。

Part=369,424,652,保存在变量中$part=@option.partnumber@

curl --location -k --request GET 'https://myprojt.test9.abc.com/api/part/config=8594&select=parts,Action,refernceNumber&SalesID=333&partNumber=$part'

当我调用 curl 命令时,动态地检查所有数字都是变量。

假设是否缺少任何数字并且预期输出为:

现有部件:部件:369,动作:新,参考编号:06 部件:652,动作:旧,参考编号:09

缺少零件:零件:424

尝试这个 shell 命令来运行它RunDeck,请帮助,谢谢

标签: shellerror-handlingconditional-statementsrundeck

解决方案


您可以通过以下方式比较两个列表。我举个例子:

<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='mylist' value='494,192,111,214' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>5a067bd8-3aa4-47eb-a522-19a5d9cdd797</id>
    <loglevel>INFO</loglevel>
    <name>ExampleList</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <exec>echo "starting"</exec>
      </command>
      <command>
        <fileExtension>.sh</fileExtension>
        <script><![CDATA[#!/bin/bash

# your list
VAR1=@option.mylist@

# hypotetical expected values
VAR2='494,192,111,214,999'

# for debug
echo "******************"
echo "Your list: $VAR1"
echo "Your expected values: $VAR2"
echo "******************"

Field_Separator=$IFS

# set comma as internal field separator for the string list
IFS=,

# store the missing values
a=()

# check two lists
for i in $VAR2; do
    found=
    for j in $VAR1; do
        if [ $i == $j ]; then
            found=1
            break
        fi
    done
    if [ ! $found ]; then
        a+=($i)
    fi
done

# now verify the possible missing values
if [[ -z "${a[*]}" ]]; then
   echo "All ok!"
else
  echo "missing values: ${a[*]}"
  # exit with error
  exit 1
fi

IFS=$Field_Separator]]></script>
        <scriptargs />
        <scriptinterpreter>/bin/bash</scriptinterpreter>
      </command>
    </sequence>
    <uuid>5a067bd8-3aa4-47eb-a522-19a5d9cdd797</uuid>
  </job>
</joblist>

这里是两个列表匹配时的结果,这里是不匹配时的结果。


推荐阅读