shell script to add "noexec" and "nosuid" to /var partition

831 Views Asked by At

I'm trying to create a small script to add noexec and nosuid to /var partition by modifying the /etc/fstab file.

Currently, the /etc/fstab also contains /var/log partition apart from /var partition.

When I run my script the changes are being made to both /var and /var/log. i only want to add "noexec" and "nosuid" to the /var partition.

Here is what I wrote

#cat test.sh
#!/bin/bash
egrep -q  '/var/.+noexec' /etc/fstab || sed -ri '/\/var/ s/defaults/defaults,noexec/' /etc/fstab
egrep -q  '/var/.+noexec' /etc/fstab || sed -ri '/\/var/ s/defaults,nodev/defaults,nodev,noexec/' /etc/fstab
egrep -q  '/var/.+nosuid' /etc/fstab || sed -ri '/\/var/ s/defaults/defaults,nosuid/' /etc/fstab
  1. current /etc/fstab entry w.r.t /var and /var/log is given below,
cat /etc/fstab

/dev/mapper/system-var  /var                    ext4    defaults,nodev        1 2

/dev/mapper/system-varlog /var/log                ext4    defaults,nodev        1 2
  1. after running script, the output is as below,
/dev/mapper/system-var  /var                    ext4    defaults,nosuid,noexec,nodev        1 2

/dev/mapper/system-varlog /var/log                ext4    defaults,nosuid,noexec,nodev        1 2
  1. The expected output is given below,
cat /etc/fstab

/dev/mapper/system-var  /var                    ext4    defaults,nosuid,noexec,nodev        1 2

/dev/mapper/system-varlog /var/log                ext4    defaults,nodev        1 2
1

There are 1 best solutions below

0
On

The simplest would be to add a traling whitespace character to your grep pattern just after /var like so:

egrep '/var\s' /etc/fstab

\s stands for whitespace in many REGEX implementations (sed, perl...), which consists of space, tab and some other characters.