比较shell脚本中的2个数组

时间:2013-05-08 14:19:02

标签: arrays shell

我已经阅读了文件夹的内容并将它们存储在一个数组中。并且需要将此数组传递给脚本。如何存储和传递数组并读取该数组??

#!/usr/bin/ksh

cd /path/applications-war
arrayWar=( $(ls /path/applications-war))

我需要将此文件夹下的所有内容放入一个数组(@arrayWar)中。 我将登录另一个框并调用脚本。我需要将此数组传递给脚本。

/usr/bin/ssh -t -t username@machinename /path/myscript.sh @arrayWar

myscript.sh 中,我想将传递的数组@arrayWar与ServicesArray进行比较。

#!/bin/ksh
 @arrayWar = $1
 ServicesArray=('abc.war' 'xyz.war')
   for warfile in @arrayWar
     do
       if  echo "${ServicesArray[@]}" | fgrep  "$warfile"; then
            echo "$warfile matches"
       else
            echo "$warfile not matched" 
       fi
    done

2 个答案:

答案 0 :(得分:2)

这是你的脚本,它将可变数量的文件作为参数:

#!/bin/ksh
ServicesArray=('abc.war' 'xyz.war')

for warfile in "${@##*/}"
  do
   if  echo "${ServicesArray[@]}" | fgrep  "$warfile"; then
        echo "$warfile matches"
   else
        echo "$warfile not matched" 
   fi
 done

您可以像这样调用脚本(请注意,建议不要使用ls):

arrayWar=( /path/applications-war/* )
/usr/bin/ssh -t -t username@machinename /path/myscript.sh "@{arrayWar[@]}"

您还可以免除arrayWar,并直接传递文件列表

/usr/bin/ssh -t -t username@machinename /path/myscript.sh /path/applications-war/*

答案 1 :(得分:0)

正如chepner指出的那样,你无法通过数组,但有几种方法可以解决这个问题。第一个是将它们作为一系列位置参数传递,我相信它们的限制是9.如果你在该数组中有超过9个项目,或者你想以更永久的方式执行此操作,你还可以相当容易在BASH中写这个(我不熟悉ksh,我做了一个快速的谷歌,语法看起来非常相似)。我将在此示例中使用ls的输出

\#!/bin/bash


\# Lets say this gives it 'myFile' and 'testFile'
ls > myArrayFile

\# Need to change IFS to accurately split the list, this splits by newline
IFS=$’\x0a’

\# Set your array
compareArray=('myFile' 'testFile' 'someOtherStuff')

\# Standard loop to compare arrays

for genItem in `cat myArrayFile`;
do
    for staticItem in $compareArray;
    do
    if $genItem == $staticItem;
        then
        echo "$genItem is in the static array"
    fi
done
done