4

Is there a way to use FreeBSDs sysrc to add comments to the file that it’s modifying?

For example, if I had an /etc/rc.conf with the standard stuff

hostname=“FreeBSDMachine”
ifconfig_em0=“DHCP”
sshd_enable=“YES”
ntpd_enable=“YES”
zfs_enable=“YES”

If I wanted to add the following:

#Set hamster_enable = “YES” to enable automatic hamster wheel performance boost; “NO” to disable
hamster_enable=“YES”

How can I do that using sysrc? I know how set the variable itself (sysrc hamster_enable=YES), but I can’t figure out how to add a comment. Is there a way to do this?

Allan
  • 1,010
  • 3
  • 15
  • 31
  • 2
    If `sysrc` in FreeBSD is anything like `rcctl` in OpenBSD, then these are tools for manipulating that file from the command line without having to look at the file or open it in an editor. Adding comments would therefore be something that `sysrc` would not need to be able to do, as it's outside the scope of its use cases. Not an answer as I'm not a FreeBSD user (so can't test). – Kusalananda May 13 '20 at 21:45

1 Answers1

2

No.

sysrc(8) does not support comments.

You do not give a lot of context but I will try to outline 2 options. Maybe they are obvious - but so is the man page for sysrc(8) ;-)

Simple addition

In many cases you are in control of the config files and can safely add things.

echo #Set hamster_enable = \“YES\” to enable automatic hamster wheel performance boost; \“NO\” to disable >> /etc/rc.conf
echo hamster_enable=\“NO\” >> /etc/rc.conf

I add the setting in the same go to keep them in order. Then you can just flip the setting at will while keep the ordering.

sysrc hamster_enable=YES

If memory fails me and sysrc does not preserve the order you can preserve order using sed

Inline editing

A typical way of handling config files before we had sysrc was to use the streaming editor sed(1). Let us first look at a couple of real life examples.

Change the DNS search suffix:

sed -I .bak 's/^search .*/search example.com/' /etc/resolv.conf

Install sudo and allow users from group wheel to sudo without using password.

pkg install -y sudo >> /var/log/postinstall.log 2>&1
sed -I .bak 's/^# %wheel ALL=(ALL) NOPASSWD: ALL/%wheel ALL=(ALL) NOPASSWD: ALL/' /usr/local/etc/sudoers

Set the port to 22 for sshd.

sed -I '' 's/^Port .*/Port 22/' /usr/jails/flavours/default/etc/ssh/sshd_config

Which leads us to the hamster

sed -I '' 's/^hamster_enable=.*/hamster_enable=\"YES\"  # Here be my comment/' /etc/rc.conf

If you insist on having comments on a different line then have a look at Sed Insert Multiple Lines

If we want to delete your lines - then the hat ^ is beginning of line.

sed -I '' 's/^#Set hamster_enable/d' /etc/rc.conf
sed -I '' 's/^hamster_enable=/d' /etc/rc.conf

While sed is more finicky than sysrc and you need to watch out for edge cases then in most cases it will be good enough.

Claus Andersen
  • 3,239
  • 1
  • 12
  • 24