<分区>
我正在尝试编写一个 bash shell 脚本,该脚本会在用户定义的时间内在嵌入式设备上消耗大量 RAM。如何在不使用数组的情况下做到这一点?
<分区>
我正在尝试编写一个 bash shell 脚本,该脚本会在用户定义的时间内在嵌入式设备上消耗大量 RAM。如何在不使用数组的情况下做到这一点?
最佳答案
即使传统Bash arrays不支持,仍然可以使用特定 shell 中内置的 eval
命令创建类似数组的变量。
以下示例脚本基于我在使用 BusyBox 时编写的一些脚本在嵌入式 Linux 项目中。 BusyBox使用 Almquist 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
使用 eval
时要小心引用!
输出:
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
在我的简短测试中,此脚本在指定的 5 分钟时间段内消耗了 ~570M 到 ~575M 物理内存*。
* 在单独的测试中使用 top 和 memprof 程序进行监控
关于linux - 编写一个 bash shell 脚本,在用户定义的时间内消耗恒定数量的 RAM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4964799/