Script for adding a disk to fstab if not existing
Elegant and short way:
#!/bin/bash
if ! grep -q 'init-poky' /etc/fstab ; then
echo '# init-poky' >> /etc/fstab
echo '/dev/sdb1 /media/poky ext4 defaults 0 2' >> /etc/fstab
fi
It uses native Bash command exit code ($?=0 for success and >0 for error code) and if grep produces error, means NOT FOUND, it does inverse (!) of result, and adds fstab entry.
Here's a simple and hopefully idiomatic solution.
grep -q 'init-poky' /etc/fstab ||
printf '# init-poky\n/dev/sdb1 /media/poky ext4 defaults 0 2\n' >> /etc/fstab
If the exit status from grep -q
is false
, execute the printf
. The ||
shorthand can be spelled out as
if grep -q 'ínit-poky' /etc/fstab; then
: nothing
else
printf ...
fi
Many beginners do not realize that the argument to if
is a command whose exit status determines whether the then
branch or the else
branch will be taken.