我使用的代碼/ bin/sh的是這樣的:!如何在unix shell中使用數組?
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
for m in $LIST1
do
echo $m
done
正如你可以看到這個目前打印出的車只作。 我怎麼能包括今年每個「回聲」的基礎上相同的位置上,讓我得到這樣的結果:
2009年
豐田2006年
本田2010
馬自達?
我使用的代碼/ bin/sh的是這樣的:!如何在unix shell中使用數組?
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
for m in $LIST1
do
echo $m
done
正如你可以看到這個目前打印出的車只作。 我怎麼能包括今年每個「回聲」的基礎上相同的位置上,讓我得到這樣的結果:
2009年
豐田2006年
本田2010
馬自達?
好,慶典確實有陣列,請參見man bash
。通用的posix shell不。
但是,外殼並不完全是一個宏處理器,所以任何元編程必須由eval
或在bash中與${!variable}
語法一起處理。也就是說,在像nroff這樣的宏處理器中,您可以通過使變量名稱爲a1,a2,a3,a4等來輕鬆地僞裝數組。
您可以在posix shell中執行該操作,但需要大量eval或等效像$(($a))
。
$ i=1 j=2; eval a$i=12 a$j=34
$ for i in 1 2; do echo $((a$i)); done
12
34
$
而對於一個特定的bash,例如...
$ a=(56 78)
$ echo ${a[0]}
56
$ echo ${a[1]}
78
$
假設慶典
array1=(mazda toyota honda)
array2=(2009 2006 2010)
for index in ${!array1[*]}
do
printf "%s %s\n" ${array1[$index]} ${array2[$index]}
done
它必須是array1 =「mazda toyota honda」否則我會得到一個語法錯誤 – goe 2009-11-28 20:54:40
以及那個shell是什麼? – 2009-11-29 03:11:38
您可以使用數組,但只是在這裏不同的是,這並不需要他們的方法:
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
paste -d' ' <(echo $LIST1 | tr ' ' '\n') <(echo $LIST2 | tr ' ' '\n')
例如,您可以使用$ IFS var僞造陣列(適用於任何posix compilant外殼):
hosts=mingw:bsd:linux:osx # for example you have the variable with all aviable hosts
# the advantage between other methods is that you have still one element and all contens get adressed through this
old_ifs=$IFS #save the old $IFS
IFS=: # say sh to seperate all commands by :
for var in $hosts ; do
# now we can use every element of $var
IFS=$old_ifs
echo $var
done
IFS=$Old_ifs
如果你把它包裝在一個函數中,你可以像真正的數組一樣使用它們
爲了提高帖子的質量,請包括爲什麼/如何解決問題。 – 2012-10-06 06:27:55
當你需要shell中的數組時,你不應該考慮使用Python嗎? – jldupont 2009-11-28 20:11:50
如果你說你正在使用哪個shell,這將有所幫助。 – 2009-11-28 21:10:57
他說他在我的shell中使用sh shell – AQU 2016-02-18 09:00:24