1

I'm trying to insert a string stored in a variable with sed as follows:

sed -i "s/^GRUB_CMDLINE_LINUX_DEFAULT.*/$kernel_options/g" /etc/default/grub

Line that I am trying to replace is: GRUB_CMDLINE_LINUX_DEFAULT=""

Variable is:

kernel_options="GRUB_CMDLINE_LINUX_DEFAULT=\"cryptdevice=${target_disk}${disk_append}2:luks:allow-discards resume=\/dev\/lvm\/swap mem_sleep_default=deep i915.enable_psr=0 i915.enable_fbc=1 i915.enable_guc=2\""

${target_disk} and ${disk_append} are determined earlier with:

target_disk=$(dialog --clear --title "Harddisk" --radiolist "Please select the target device" 0 0 0 \
    $(ls /dev/sd? /dev/vd? /dev/mmcblk? /dev/nvme?n? -1 2> /dev/null | while read line; do
echo "$line" "$line" on; done) 3>&1 1>&2 2>&3)
if test $? -eq 1; then exit 1; fi
if grep -q "mmcblk" <<< $target_disk || grep -q "nvme" <<< $target_disk; then
    disk_append=p
fi

I can't seem to get the sed part working, any suggestions how to improve this are appreciated.

Thank you in advance.

6372656570
  • 11
  • 1
  • The sed part looks good to me....what is the output of echo $kernel_options, and how are you setting kernel_options? are you exporting it? – Ricardo Apr 08 '21 at 21:24
  • 1
    Since the replacement string contains sed metachacacters, they need to be escaped. Do [this](https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern/2705678#2705678) and [this](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed/29613573#29613573) solve the problem? – Gordon Davisson Apr 08 '21 at 21:25

2 Answers2

0

Thank you very much, Gordon Davisson.

It works if I create a second variable like so:

kernel_options="GRUB_CMDLINE_LINUX_DEFAULT=\"cryptdevice=${target_disk}${disk_append}2:luks:allow-discards resume=/dev/lvm/swap mem_sleep_default=deep i915.enable_psr=0 i915.enable_fbc=1 i915.enable_guc=2\""

escaped_kernel_options=$(printf '%s\n' "$kernel_options" | sed -e 's/[]\/$*.^[]/\\&/g');

sed -i "s/^GRUB_CMDLINE_LINUX_DEFAULT.*/$escaped_kernel_options/g" /etc/default/grub
6372656570
  • 11
  • 1
0

How about using a and d instead of s?

sed -i "/^GRUB_CMDLINE_LINUX_DEFAULT/{
a $kernel_options
d}" /etc/default/grub
etsuhisa
  • 1,698
  • 1
  • 5
  • 7