10

First of all, I have read many posts (see at bottom) with if-clauses to search in a file for a specific string and followed these posts 1to1, however I don't manage to get my script to work. I want to make an entry in /etc/fstab if it doesn't exist yet:

#!/bin/bash
fstab=/etc/fstab

if grep -q "poky-disc" "$fstab"
then
    echo "#poky-disc" >> /etc/fstab
    echo "/dev/sdb1 /media/poky ext4 defaults 0 2" >> /etc/fstab
else
    echo "Entry in fstab exists."
fi

Thanks for your help in advance. These are the similar posts, which didnt help me further:

codeforester
  • 34,080
  • 14
  • 96
  • 122
h0ch5tr4355
  • 1,677
  • 2
  • 24
  • 42

4 Answers4

7

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.

tripleee
  • 158,107
  • 27
  • 234
  • 292
6

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.

Arunas Bartisius
  • 1,421
  • 19
  • 20
2

I had the same issue. I managed to edit it with this command:

sudo su -c "echo '#test' >> /etc/fstab"
0
#!/bin/bash
fstab=/etc/fstab

if [[ $(grep -q "poky-disc" "$fstab") ]]
# forgiving me for being a bit of over-rigorous, you might want to change this matching word, as below, 'poky-disc' merely a comment, not exactly a config line, so
then
    echo "#poky-disc" >> /etc/fstab
    echo "/dev/sdb1 /media/poky ext4 defaults 0 2" >> /etc/fstab
else
    echo "Entry in fstab exists."
fi
kyokose
  • 81
  • 1
  • 8
  • Thank you! Could you also explain the usage of the 2nd line "fstab=/etc/fstab" here? – Yiping Sep 07 '18 at 14:39
  • Creating an `fstab` variable doesn't make much sense as it is written. First of all it's always going to be `/etc/fstab`, but even if it were to change it wouldn't be helpful as you're not consistent in using the variable. – skyking Sep 18 '18 at 17:14
  • The command substitution is completely wrong here. You are checking if `grep -q` outputs a non-empty string, which of course it will never do. You simply want `if ! grep -q "poky-disc" "$fstab"; then` – tripleee Aug 26 '19 at 12:25
  • FWIW, this error is a duplicate of https://stackoverflow.com/questions/36371221/bash-if-statement-too-many-arguments – tripleee Sep 20 '21 at 05:49