如何使用 sed 命令更改 limits.conf 中的 ulimit 值?

How to change ulimit value in limits.conf using sed command?

我想使用 shell 脚本在 limits.conf 中附加更改(如果不存在)。两种情况:

  1. 如果未指定限制,我必须使用 sed 添加。
  2. 如果存在限制,则不应更改。
*   soft   nofile  100000
*   hard   nofile  150000

当给定的类型和项目不存在于 limits.conf:

LINE_TO_APPEND='*               hard    nofile          512'
read -a line_array <<< "$LINE_TO_APPEND"
line_type=${line_array[1]} # consists of just normal characters
line_item=${line_array[2]} # consists of just normal characters
if [[ -z $(grep "$line_type  *$line_item" limits.conf) ]]; then
   echo "$LINE_TO_APPEND" >> limits.conf
fi

如果你想要一个更纯粹的 sed 方法,下面带有硬编码字段的不太通用的命令将起作用(我陷入了 "escaping hell" 试图使用 $;稍后我会尝试重新访问此答案!):

sed -i 'H;1h;$!d;x;/soft  *nofile/!s/$/\n*   soft   nofile  100000/' limits.conf

sed解决方案的解释: