2

I have to edit /etc/fstab to change mounting options for /dev/shm parameter.

source line is :

tmpfs                   /dev/shm                tmpfs   size=11g        0 0

I want to add noexec to the fourth field (mounting options) for the /dev/shm partition for many of servers.(with different size in mounting options) So I tiried this code: To obtain the value of mounting options. I used:

shmvar=`grep -E '\s/dev/shm\s' /etc/fstab | awk '{ print $4 }'`

the output is : size=11g

sed -i -e '/shm/s/$shmvar/$shmvar,noexec/' /etc/fstab

OR

sed -i -e '/shm/s/$shmvar/&,noexec/' /etc/fstab

but none of the sed commands worked.

while I use "size=11g" instead of "$shmvar" it works:

 sed -i -e '/shm/s/size=11g/size=11g,noexec/' /etc/fstab
OR
sed -i -e '/shm/s/size=11g/&,noexec/' /etc/fstab

But because the "size" value is different in servers, I have to use variables

Would highly appreciate some quick help. Thanks

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Babak.K
  • 23
  • 2

1 Answers1

4

With GNU awk. If second field contains /dev/shm then append ,noexec to fourth field.

awk -i inplace 'BEGIN{ OFS="\t" } $2=="/dev/shm"{ $4=$4 ",noexec" } { print }' file

Output:

tmpfs   /dev/shm        tmpfs   size=11g,noexec 0       0
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Thanks a lot , it works Is there any way to change directly the fstab file ? – Babak.K Jan 02 '22 at 11:49
  • Yes, I've updated my answer. – Cyrus Jan 02 '22 at 11:51
  • 2
    Assuming the input file is tab-separated since you're making it tab-separated in the output, you should probably change `OFS="\t"` to `FS=OFS="\t"` so it won't fail if any of the fields are empty or contain blanks, e.g. maybe `/dev/shm` could be `/dev/foo bar`, idk. – Ed Morton Jan 02 '22 at 13:50