[英]Comparing 2 Arrays in shell script
我已經閱讀了文件夾的內容,並將其存儲在數組中。 並且需要將此數組傳遞給腳本。 如何存儲和傳遞數組並讀取該數組?
#!/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
這是您的腳本,該腳本使用可變數量的文件作為參數:
#!/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/*
正如chepner指出的那樣,您不能傳遞數組,但是有兩種方法可以解決此問題。 第一種是將它們作為一系列位置參數傳遞,我認為這些參數的限制為9。如果該數組中有9個以上的項,或者您希望以更永久的方式進行操作,則還可以相當容易用BASH編寫(我不熟悉ksh,我做了一個快速的Google,語法看起來也很相似)。 在此示例中,我將使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.