-1

I want to append changes in limits.conf if not exists using shell script. Two cases:

  1. If limit not specified, I have to add using sed.
  2. If limit exists, it should not change.
*   soft   nofile  100000
*   hard   nofile  150000
Community
  • 1
  • 1
Saleem
  • 41
  • 6
  • This is not a duplicate of the linked question. That is just a straight-forward **sed** substitution. _This_ question requires a test of whether or not certain information is already present in `limits.conf` and, if not, then append a new line. – Joseph Quinsey Dec 03 '19 at 13:45
  • And in the linked question, [How do I use sed to change my configuration files, with flexible keys and values?](//stackoverflow.com/q/5955548), none of the answers actually work. The OP's requirement there was that "... both `central.database` and `SQLTEST` come from bash variables". However, all the answers assumed the hard-coded value of `central.database` or whatever so that they could manually escape the dot `.`, rather than dealing with an arbitrary bash variable. (Indeed, many answerers forgot that `.` was special in **sed**.) – Joseph Quinsey Dec 03 '19 at 14:31

1 Answers1

1

This bash script will add $LINE_TO_APPEND to the end of limits.conf when the given type and item is not already present in 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

If you want a more purely sed approach, the following less-generic command with hard-coded fields will work (I got caught up in "escaping hell" trying to use $; I'll try revisiting this answer later!):

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

Explanation of sed solution:

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77