即使是传统的Bash 数组 http://tldp.org/LDP/abs/html/arrays.html不支持,仍然可以使用创建类似数组的变量eval
内置于特定 shell 中的命令。
以下示例脚本基于我在使用时所做的一些脚本BusyBox http://www.busybox.net/在一个嵌入式Linux项目中。BusyBox http://www.busybox.net/使用阿尔姆奎斯特壳 http://en.wikipedia.org/wiki/Ash_shell(也称为 A Shell、ash 和 sh),不支持数组。
#!/bin/ash
for index in 1 2 3 4 5; do
value=$(($index * 1024))
eval array$index=\"array[$index]: $value\"
done
for i in 1 3 5; do
eval echo \$array$i
done
Be careful with quoting when using eval
!
Output:
array[1]: 1024
array[3]: 3072
array[5]: 5120
根据您的特定场景,类似于以下的脚本可能就足够了。
#!/bin/ash
echo "Provide sleep time in the form of NUMBER[SUFFIX]"
echo " SUFFIX may be 's' for seconds (default), 'm' for minutes,"
echo " 'h' for hours, or 'd' for days."
read -p "> " delay
echo "begin allocating memory..."
for index in $(seq 1000); do
value=$(seq -w -s '' $index $(($index + 100000)))
eval array$index=$value
done
echo "...end allocating memory"
echo "sleeping for $delay"
sleep $delay
In my brief testing, this script consumed ~570M to ~575M physical memory* for the specified time period of 5 minutes.
* Monitored using top and memprof programs in separate tests