如何在Shell脚本中优雅地处理内存不足

jot*_*tik 12 bash shell out-of-memory

有没有办法在Shell脚本中正常处理内存不足的情况?

$ cat test.sh
#!/bin/sh
i=asdf
while true; do
  i="$i $i"
done
$ bash test.sh
test.sh: xrealloc: cannot allocate 18446744072098939008 bytes
Run Code Online (Sandbox Code Playgroud)

许多编程语言都允许使用简单的try-catch构造来处理内存不足异常。是否有可能在shell脚本/ Bash中适当地处理内存不足的情况?怎么样?

是否可以释放临时缓冲区并尝试继续执行,还是可以执行一些自定义错误处理(保存状态)并退出并出现错误?

tk4*_*421 1

据我所知。相反,当您遇到这样的问题时,正常的方法是通过 提高限制ulimit

ulimit -m N # for the heap
ulimit -s N # for the stack
Run Code Online (Sandbox Code Playgroud)

但是,要以编程方式检测它,您必须执行类似于strace和 watch for 的功能ENOMEM